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

with lib;
let
  serverPackages = with pkgs; [ emacs-nox reboot-if-necessary test-config ];

  reboot-if-necessary = pkgs.writeShellScriptBin "reboot-if-necessary" ''
    if [ $# -ne 1 ]; then
      echo "FAILED: no sync file provided."
      exit 1
    fi

    WALL=${pkgs.utillinux}/bin/wall

    if [ -f $1 ]; then
      $WALL "$1 exists, rebooting system"
      ${pkgs.systemd}/bin/reboot
    else
      $WALL "$1 does not exist, switching config."
      nixos-rebuild switch
    fi

    exit 0
  '';

  test-config = pkgs.writeShellScriptBin "fudo-test-config" ''
    if [ $# -gt 1 ]; then
      echo "usage: $0 [timeout]"
      exit 1
    elif [ $# -eq 1 ]; then
      TIMEOUT=$1
    else
      TIMEOUT=15m
    fi

    SYNCFILE=$TMP/sync-$(date +"%Y%m%d-%H%M%N")
    touch $SYNCFILE
    ${pkgs.utillinux}/bin/wall "Launching config. System will restart in $TIMEOUT if $SYNCFILE still exists."
    systemd-run --on-active=$TIMEOUT ${reboot-if-necessary} $SYNCFILE
    nixos-rebuild test

    exit 0
  '';

in {
  imports = [ ./common.nix ];

  config = {
    environment = { systemPackages = serverPackages; };

    system.autoUpgrade.enable = false;

    networking.networkmanager.enable = mkForce false;

    services = { xserver.enable = false; };

    sound.enable = false;
    hardware.pulseaudio.enable = false;

    powerManagement =
      if config.fudo.hosts.${config.instance.hostname}.keep-cool then {
        enable = true;
        cpuFreqGovernor = "ondemand";
      } else {
        enable = false;
      };

    systemd.targets = {
      sleep.enable = false;
      suspend.enable = false;
      hibernate.enable = false;
      hybrid-sleep.enable = false;
    };
  };
}