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

with lib;
let
  # Available to all users on the system. Keep it minimal.
  global-packages = with pkgs; [ bind git heimdal openssh_gssapi vim wget ];

in {
  environment = {
    etc.current-nixos-config.source = ../../.;

    systemPackages = global-packages;

    shellInit = ''
      ${pkgs.gnupg}/bin/gpg-connect-agent /bye
      export SSH_AUTH_SOCK=$(${pkgs.gnupg}/bin/gpgconf --list-dirs agent-ssh-socket)
    '';
  };

  nixpkgs.config.allowUnfree = true;
  security.acme.acceptTerms = true;

  krb5 = {
    enable = true;

    appdefaults = {
      forwardable = true;
      proxiable = true;
      encrypt = true;
      forward = true;
    };

    libdefaults = {
      allow_weak_crypto = false;
      dns_lookup_kdc = true;
      dns_lookup_realm = true;
      forwardable = true;
      proxiable = true;
    };

    kerberos = pkgs.heimdalFull;
  };

  services = {
    openssh = {
      enable = true;
      startWhenNeeded = true;
      useDns = true;
      permitRootLogin = "prohibit-password";
      extraConfig = ''
        GSSAPIAuthentication yes
        GSSAPICleanupCredentials yes
        GSSAPIKeyExchange yes
        GSSAPIStoreCredentialsOnRekey yes
      '';
      # FIXME: add all the hosts we know about
      knownHosts = {
        # publicKey, hostNames
      };
    };

    lshd = {
      enable = true;
      portNumber = 2112;
      rootLogin = true;
      srpKeyExchange = true;
      tcpForwarding = false;
      publicKeyAuthentication = true;
      passwordAuthentication = false;
    };

    fail2ban = {
      enable = true;
      bantime-increment.enable = true;
    };

    xserver = {
      layout = "us";
      xkbVariant = "dvp";
      xkbOptions = "ctrl:nocaps";
    };

    # pcscd.enable = true;
    # udev.packages = with pkgs; [ yubikey-personalization ];
  };

  networking.firewall = {
    # Allow mosh connections if the firewall is enabled
    allowedUDPPortRanges = [{
      from = 60000;
      to = 60100;
    }];
  };

  console.useXkbConfig = true;

  i18n.defaultLocale = "en_US.UTF-8";

  programs = {
    mosh.enable = true;

    bash.enableCompletion = true;

    fish.enable = true;

    gnupg.agent = {
      enable = true;
      enableSSHSupport = true;
      # pinentryFlavor = if cfg.enable-gui then "gnome3" else "curses";
    };

    ssh = {
      # Use GPG agent instead
      startAgent = false;

      package = pkgs.openssh_gssapi;

      extraConfig = ''
        GSSAPIAuthentication yes
        GSSAPIDelegateCredentials yes
      '';
    };
  };

  security.pam = {
    enableSSHAgentAuth = true;

    services = {
      sshd = {
        makeHomeDir = true;
        sshAgentAuth = true;
        # This isn't supposed to ask for a code unless ~/.google_authenticator exists...but it does
        # googleAuthenticator.enable = true;
      };
    };
  };

  services.dbus.socketActivated = true;
}