# Out-of-tree apple-bce (Buffer Copy Engine) for Apple T2.
# Upstream suspend fixes: https://github.com/deqrocks/apple-bce (branch no-state-suspend).
{
  lib,
  stdenv,
  fetchFromGitHub,
  kernel,
  kernelModuleMakeFlags,
}:
let
  pname = "apple-bce";
  branch = "no-state-suspend";
  version = "0-unstable-2026-04-07";
  rev = "7cad7c8fb2a03825377de3d9a7beceaa73b197b5";
in
stdenv.mkDerivation {
  inherit pname version;
  name = "${pname}-${version}-${kernel.version}";

  src = fetchFromGitHub {
    owner = "deqrocks";
    repo = "apple-bce";
    inherit rev;
    hash = "sha256-oHO3rl1ODDncMfIwW3R3od07dudN5jqY1W6u1gpQHUE=";
  };

  hardeningDisable = [ "pic" ];

  nativeBuildInputs = kernel.moduleBuildDependencies;

  makeFlags = kernelModuleMakeFlags ++ [
    "KDIR=${kernel.dev}/lib/modules/${kernel.modDirVersion}/build"
  ];

  installPhase = ''
    runHook preInstall
    install -D apple-bce.ko $out/lib/modules/${kernel.modDirVersion}/extra/apple-bce.ko
    runHook postInstall
  '';

  meta = {
    description = "Apple T2 Buffer Copy Engine driver (deqrocks fork with suspend fixes)";
    homepage = "https://github.com/deqrocks/apple-bce";
    license = lib.licenses.gpl2Only;
    platforms = lib.platforms.linux;
    maintainers = [ ];
  };
}
