{ stdenv, requireFile, fetchpatch, kernel, lib }:

stdenv.mkDerivation rec {
  pname = "decklink";
  version = "12.2.2";

  src = requireFile {
    name = "Blackmagic_Desktop_Video_Linux_12.2.2.tar.gz";
    url = "https://www.blackmagicdesign.com/support/";
    sha256 = "8bca946bd3f002d2d404a74210c881935351e1a0d03f750559b180fdb439ef35";
  };

  KERNELDIR = "${kernel.dev}/lib/modules/${kernel.modDirVersion}/build";
  INSTALL_MOD_PATH = placeholder "out";

  nativeBuildInputs =  kernel.moduleBuildDependencies;

  setSourceRoot = ''
    tar xf Blackmagic_Desktop_Video_Linux_12.2.2/other/x86_64/desktopvideo-12.2.2a6-x86_64.tar.gz
    sourceRoot=$NIX_BUILD_TOP/desktopvideo-12.2.2a6-x86_64/usr/src
  '';

  buildPhase = ''
    runHook preBuild

    make -C $sourceRoot/blackmagic-12.2.2a6 -j$NIX_BUILD_CORES
    make -C $sourceRoot/blackmagic-io-12.2.2a6 -j$NIX_BUILD_CORES

    runHook postBuild
  '';

  installPhase = ''
    runHook preInstall

    make -C $KERNELDIR M=$sourceRoot/blackmagic-12.2.2a6 modules_install
    make -C $KERNELDIR M=$sourceRoot/blackmagic-io-12.2.2a6 modules_install

    runHook postInstall
  '';

  meta = with lib; {
    homepage = "https://www.blackmagicdesign.com/support/family/capture-and-playback";
    maintainers = [ maintainers.hexchen ];
    license = licenses.unfree;
    description = "Kernel module for the Blackmagic Design Decklink cards";
    platforms = platforms.linux;
  };
}
