{ lib
, runCommand
, fetchFromGitHub
, fetchurl
, fetchzip
, ... }:

let
  mkTf2Package =
    { pname
    , version ? null
    , cfg ? []
    , custom ? []
    , env ? {}
    }@args:
    let name = "${pname}${lib.optionalString (version != null) "-${version}"}";
    in runCommand name env ''
      ${lib.toShellVar "cfgs" cfg}
      ${lib.toShellVar "customs" custom}
      set -xe
      mkdir -p $out/cfg $out/custom

      for i in "''${cfgs[@]}"; do
        ln -s "$i" "$out/cfg/$(basename "$i")"
      done

      for i in "''${customs[@]}"; do
        ln -s "$i" "$out/custom/$(basename "$i")"
      done
    '';

  mkCfg = name: body:
    runCommand name {} ''
      ${lib.toShellVar "name" name}
      mkdir -p $out/cfg "$(dirname "$out/cfg/$name")"
      tee "$out/cfg/$name.cfg" << SUPER_UNIQUE_EOF
      // Generated by tf2.nix

      ${body}
      SUPER_UNIQUE_EOF
    '';

  mkTf2PackageFromDir = path:
    runCommand "tf2-dir" {} ''
      cp -r "${path}" $out
    '';

  fetchFromGameBanana =
    { id
    , hash
    }:
    fetchzip {
      url = "https://gamebanana.com/dl/${id}";
      extension = "zip";
      inherit hash;
    };

  mastercomfig = import ./packages/mastercomfig.nix {
    inherit mkTf2Package;
    inherit fetchurl;
  };
in {
  inherit mkTf2Package mastercomfig mkCfg mkTf2PackageFromDir;

  huds.deerhud = mkTf2Package {
    pname = "deerhud";
    version = "78a24ef";
    custom = [
      (fetchFromGitHub {
        name = "deerhud";
        owner = "DeerUwU";
        repo = "deerhud-tf2";
        rev = "78a24effbc66bc78b4bb557228eaa0195db3270c";
        hash = "sha256-uwKRilkEPHk1snjH/n9u32dMXr3cXjYN06cfthpZe7g=";
      })
    ];
  };

  loadouts-script = mkTf2Package rec {
    pname = "tf2-loadouts-script";
    version = "3.1";
    custom = [
      (fetchurl {
        url = "https://github.com/jooonior/tf2-loadouts-script/releases/download/v${version}/loadouts.vpk";
        hash = "sha256-qMDQe/lLZz5YdH6kvG7vNKHUxPvId4AMqu/hFqr/Sd8=";
      })
    ];
  };

  improved-crosshairs = mkTf2Package {
    pname = "improved-crosshairs";
    custom = [
      (fetchFromGameBanana {
        id = "1047153";
        hash = "sha256-ULcSfxuiGY1YCE1zQ693183F7ZRC11tYhvDMJKyzL1A=";
      })
    ];
  };
}
