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

{
  options.c3d2.baremetal = lib.mkEnableOption "baremetal";

  config = let
    initrdEd2219Key = "/etc/ssh/initrd/ssh_host_ed25519_key";
    initrdRsaKey = "/etc/ssh/initrd/ssh_host_rsa_key";
  in lib.mkIf config.c3d2.baremetal {
    assertions = [
      {
        assertion = config.boot.initrd.network.ssh.enable -> (config.boot.initrd.availableKernelModules != []);
        message = "boot.initrd.availableKernelModules must be set for initrd networking to reliably work!";
      }
    ];

    boot = {
      initrd.network = {
        enable = true;
        ssh = {
          # TODO: enable now per machine
          # enable = true;
          authorizedKeys = config.users.users.root.openssh.authorizedKeys.keys;
          hostKeys = [
            initrdEd2219Key
            initrdRsaKey
          ];
          port = 4748;
        };
        postCommands = ''
          cat <<EOF > /root/.profile
          cryptsetup-askpass
          EOF
        '';
      };
      kernelParams = [
        # "boot.shell_on_fail"
        "zfs_force=1"
      ];
    };

    environment.systemPackages = with pkgs; [
      freeipmi
      lshw
      pciutils # lscpi
      smartmontools # for smartctl
    ];

    nix.settings.system-features = [
      "kvm" "big-parallel" "nixos-test" "benchmark"
    ];

    powerManagement.cpuFreqGovernor = "schedutil";

    services = {
      # just assume there are ssd's everywhere
      fstrim.enable = true;
      smartd.enable = true;
    };

    system.activationScripts.generateInitrdOpensshHostKeys = let
      sshKeygen = "${config.programs.ssh.package}/bin/ssh-keygen";
    in lib.mkIf config.boot.initrd.network.ssh.enable ''
      if [[ ! -e ${initrdEd2219Key} || ! -e ${initrdRsaKey} ]]; then
        echo "Generating initrd OpenSSH hostkeys..."
        mkdir -m700 -p /etc/ssh/initrd/
        ${sshKeygen} -t ed25519 -N "" -f ${initrdEd2219Key}
        ${sshKeygen} -t rsa -b 4096 -N "" -f ${initrdRsaKey}
      fi

      if [[ -e ${initrdRsaKey} && $(${sshKeygen} -l -f ${initrdRsaKey} | ${pkgs.gawk}/bin/awk '{print $1}') == 3072 ]]; then
        echo "Upgrading RSA initrd OpenSSH hostkey with only 3072 bit..."
        rm -f ${initrdRsaKey} ${initrdRsaKey}.pub
        ${sshKeygen} -t rsa -b 4096 -N "" -f ${initrdRsaKey}
      fi
    '';

    zramSwap.enable = true;
  };
}
