{ depot, pkgs, ... }:

let
  nodejs = pkgs.nodejs-16_x;
  composition = pkgs.callPackage ./node-overrides.nix { inherit nodejs; };
  inherit (composition.shell) nodeDependencies;
in
pkgs.stdenv.mkDerivation {
  name = "lukegbcom-export";
  src = pkgs.nix-gitignore.gitignoreSourcePure [
    ".next"
    "out"
    "build"
    ".pnp"
    "node_modules"
    ".pnp.js"
    "*.nix"
    "*.sh"
    "*.log"
    "package.json"
    "result*"
  ] ./.;
  buildInputs = [ nodejs ];
  postPatch = let
    f0Firmware = depot.nix.pkgs.flipperzero-firmware;
  in ''
    sed -i \
      -e 's/__FLIPPER_FIRMWARE_NAME__/${f0Firmware.name}/g' \
      -e 's/__FLIPPER_FIRMWARE_VERSION__/${f0Firmware.version}/g' \
      -e 's/__FLIPPER_UPSTREAM_VERSION__/${f0Firmware.upstreamVersion}/g' \
      pages/tools.js
  '';
  buildPhase = ''
    ln -s ${nodeDependencies}/lib/node_modules ./node_modules
    export PATH="${nodeDependencies}/bin:$PATH"

    echo Starting build
    next build

    echo Starting static export
    next export
  '';
  installPhase = ''
    echo Done - moving to output
    mkdir $out
    cp firebase.json $out/firebase.json
    cp .firebaserc $out/.firebaserc
    mv out $out/out
  '';
}