{ pkgs ? import <nixpkgs> {}
, ... }:

let
  heatshrink2 = pm: pm.buildPythonPackage rec {
    pname = "heatshrink2";
    version = "0.11.0";

    src = pkgs.fetchFromGitHub {
      owner = "eerimoq";
      repo = "pyheatshrink";
      rev = version;
      hash = "sha256:1122abg9yf3shbb3h6kzh8f8vmhgxy1w9ck0mjg1zqyncry2hwiz";
      fetchSubmodules = true;
    };

    propagatedBuildInputs = with pm; [
      cython
    ];
  };
  python-with-deps = pkgs.python3.withPackages (pm: with pm; [
    pillow
    (heatshrink2 pm)
    protobuf
    setuptools
    pyserial
    grpcio
    grpcio-tools
  ]);
  deps = with pkgs; [
    gcc-arm-embedded
    openocd
    clang
    dfu-util
    git
    protobuf
    python-with-deps
  ];
in
pkgs.stdenvNoCC.mkDerivation rec {
  pname = "flipper-firmware";
  version = "0.65.3-0827-RMv2";

  src = pkgs.fetchFromGitHub {
    owner = "RogueMaster";
    repo = "flipperzero-firmware-wPlugins";
    rev = version;
    fetchSubmodules = true;
    sha256 = "01kdv4rld3ahp0wgb4ha0q2l8gspk7033li1bm5jgzggrkhyvgv1";
  };

  patches = [
    ./fbt_assets_protobuf_version_from_changelog.patch
  ];

  nativeBuildInputs = deps;

  FBT_NOENV = 1;
  FBT_NO_SYNC = 1;
  buildPhase = ''
    runHook preBuild

    mkdir -p $NIX_BUILD_TOP/bin
    ln -s $(command -v arm-none-eabi-gcc) $NIX_BUILD_TOP/bin/arm-none-eabi-cc
    export PATH=$NIX_BUILD_TOP/bin:$PATH

    ./fbt -j$NIX_BUILD_CORES --with-updater COMPACT=1 DEBUG=0 updater_package

    runHook postBuild
  '';

  installPhase = ''
    runHook preInstall

    cp -r dist/f7-C $out

    runHook postInstall
  '';

  passthru.deps = deps;
}