{ lib, pkgs, inputs, config, ... }:
let
  # Two-stage callPackage matches nixos-hardware apple/t2 generic.nix.
  linuxT2GenericFromDir =
    { lib, ... }@args:
    { kernel, t2linuxPatchesSrc }:
    let
      patchNames = lib.sort lib.lessThan (
        lib.filter (n: builtins.match "^[0-9]{4}-.*\\.patch$" n != null) (
          lib.attrNames (builtins.readDir t2linuxPatchesSrc)
        )
      );
      t2Patches = map
        (name: {
          inherit name;
          patch = "${t2linuxPatchesSrc}/${name}";
        })
        patchNames;
    in
    kernel.override (
      args
      // {
        pname = "linux-t2";
        structuredExtraConfig = with lib.kernel; {
          # In-tree staging driver disabled; we ship deqrocks/apple-bce via boot.extraModulePackages.
          APPLE_BCE = no;
          APPLE_GMUX = module;
          APFS_FS = module;
          BRCMFMAC = module;
          BT_BCM = module;
          BT_HCIBCM4377 = module;
          BT_HCIUART_BCM = yes;
          BT_HCIUART = module;
          HID_APPLETB_BL = module;
          HID_APPLETB_KBD = module;
          HID_APPLE = module;
          HID_MAGICMOUSE = module;
          DRM_APPLETBDRM = module;
          HID_SENSOR_ALS = module;
          SND_PCM = module;
          STAGING = yes;
        };
        kernelPatches = t2Patches ++ (args.kernelPatches or [ ]);
        argsOverride.extraMeta = {
          description = "The Linux kernel (with patches from the T2 Linux project)";
          maintainers = with lib.maintainers; [ soopyc ];
        };
      }
      // (args.argsOverride or { })
    );

  # linux_6_19 was dropped from nixpkgs; t2linux/linux-t2-patches HEAD targets 7.x (see 76589a8).
  linuxT2Kernel = (pkgs.callPackage linuxT2GenericFromDir { }) {
    kernel = pkgs.linux_latest;
    t2linuxPatchesSrc = inputs.t2linux-patches;
  };
in
{
  boot.kernelPackages = lib.mkForce (pkgs.linuxPackagesFor linuxT2Kernel);

  # https://github.com/deqrocks/apple-bce (branch no-state-suspend) — BCE + suspend-oriented fixes.
  # README also mentions companion userspace: t2-upower, t2-kbd-tb (not packaged here yet).
  boot.extraModulePackages = [
    (config.boot.kernelPackages.callPackage ./apple-bce.nix { })
  ];
}
