{ config, lib, pkgs, ... }:

let
  controlUser = "builder";
in {
  system.stateVersion = "25.05";

  boot.kernelParams = [
    "console=tty0"
    "console=ttyS0,115200n8"
    "net.ifnames=0"
    "biosdevname=0"
  ];
  boot.loader.timeout = 0;

  networking.hostName = "spies-gpu-builder";
  networking.useDHCP = lib.mkDefault false;
  networking.useNetworkd = lib.mkDefault true;
  networking.nameservers = [
    "2606:4700:4700::1111"
    "2606:4700:4700::1001"
  ];
  networking.firewall.enable = true;
  networking.firewall.allowedTCPPorts = [ 22 ];

  systemd.network.enable = true;

  services.openssh = {
    enable = true;
    settings = {
      KbdInteractiveAuthentication = false;
      PasswordAuthentication = false;
      PermitRootLogin = "prohibit-password";
    };
  };

  security.pam.services.sshd.rules.account.unix.enable = false;
  security.pam.services.sshd.rules.account.permit = {
    order = config.security.pam.services.sshd.rules.account.unix.order;
    control = "required";
    modulePath = "${config.security.pam.package}/lib/security/pam_permit.so";
  };

  users.users.${controlUser} = {
    isNormalUser = true;
    description = "GPU builder control user";
    home = "/home/${controlUser}";
    createHome = true;
    extraGroups = [ "systemd-journal" ];
    shell = pkgs.bashInteractive;
    hashedPassword = "!";
  };

  nix.settings = {
    experimental-features = [ "nix-command" "flakes" ];
    sandbox = false;
    trusted-users = [ "root" controlUser ];
    system-features = lib.mkDefault [ "benchmark" "big-parallel" ];
    builders-use-substitutes = true;
    max-jobs = "auto";
    cores = 0;  # 0 = use all available cores per build
    build-dir = "/nix/var/tmp/nix-build";
  };

  environment.variables.TMPDIR = "/nix/tmp";
  systemd.tmpfiles.rules = [
    "d /nix 0755 root root -"
    "d /nix/tmp 1777 root root -"
    "d /nix/var 0755 root root -"
    "d /nix/var/tmp 0755 root root -"
    "d /nix/var/tmp/nix-build 0755 root root -"
  ];

  # Generic builder tools only — no project-specific runtimes or models.
  environment.systemPackages = with pkgs; [
    ffmpeg
    git
    git-lfs
    jq
    tmux
    vim
  ];

  # Generic CUDA-capable builder baseline. Concrete system-features are set by
  # the builder entrypoint from rescue facts so CPU canaries do not advertise
  # cuda and real GPU hosts do.
  services.xserver.videoDrivers = [ "nvidia" ];
  hardware.graphics.enable = true;
  hardware.nvidia = {
    modesetting.enable = true;
    powerManagement.enable = false;
    open = false;
    nvidiaSettings = false;
    package = config.boot.kernelPackages.nvidiaPackages.production;
  };
}
