# SPDX-FileCopyrightText: 2020 Luke Granger-Brown <depot@lukegb.com>
#
# SPDX-License-Identifier: Apache-2.0

{ pkgs, depot, lib, rebuilder, ... }:
let 
  inherit (lib) mkDefault;
in
{
  hardware.enableRedistributableFirmware = true;

  nix = {
    nixPath = [ "depot=/home/lukegb/depot/" "nixpkgs=/home/lukegb/depot/third_party/nixpkgs/" ];
    trustedUsers = [ "root" "@wheel" ];
    binaryCaches = lib.mkForce [ "https://cache.nixos.org/" "s3://lukegb-nix-cache?endpoint=storage.googleapis.com&trusted=1" ];
    trustedBinaryCaches = lib.mkForce [ "https://cache.nixos.org/" "s3://lukegb-nix-cache?endpoint=storage.googleapis.com&trusted=1" ];
    envVars = {
      AWS_ACCESS_KEY_ID = "${depot.ops.secrets.nixCache.AWS_ACCESS_KEY_ID}";
      AWS_SECRET_ACCESS_KEY = "${depot.ops.secrets.nixCache.AWS_SECRET_ACCESS_KEY}";
    };
  };
  nixpkgs.config = depot.third_party.nixpkgsConfig;

  i18n.defaultLocale = "en_GB.UTF-8";
  console.keyMap = "us";

  time.timeZone = mkDefault "Etc/UTC";

  environment.systemPackages = with pkgs; [
    vim rxvt_unicode.terminfo tmux rebuilder tailscale rsync
    (mercurial.overridePythonAttrs (origAttrs: {
      propagatedBuildInputs = origAttrs.propagatedBuildInputs ++ [python3Packages.hg-evolve depot.nix.pkgs.hg-git];
    }))
  ];

  networking.firewall = {
    allowPing = true;
  };

  users.mutableUsers = false;
  users.users = let secrets = depot.ops.secrets; in {
    root.hashedPassword = secrets.passwordHashes.root;
    lukegb = {
      isNormalUser = true;
      uid = 1000;
      extraGroups = [ "wheel" ];
      hashedPassword = secrets.passwordHashes.lukegb;
    };
    deployer = {
      isSystemUser = true;
      uid = 1001;
      hashedPassword = "!";
      useDefaultShell = true;
      home = "/var/lib/deployer";
      createHome = true;
      openssh.authorizedKeys.keyFiles = [
        ../../secrets/deployer_ed25519.pub
      ];
    };
  };
  security.sudo.extraRules = [{
    users = [ "deployer" ];
    commands = [{
      command = "${rebuilder}/bin/rebuilder";
      options = [ "NOPASSWD" ];
    }];
  }];
  security.sudo.extraConfig = ''
    Defaults:deployer !requiretty
  '';

  programs.mtr.enable = true;
  services.openssh.enable = true;
  services.tailscale.enable = true;

  boot = {
    kernelModules = [ "tcp_bbr" ];
    kernel.sysctl."net.ipv4.tcp_congestion_control" = "bbr";
    kernel.sysctl."net.core.default_qdisc" = "fq_codel";
  };

  system.activationScripts.lukegb-hgrc = lib.stringAfter [ "users" "groups" ] ''
    ln -sfn ${./hgrc} /home/lukegb/.hgrc
  '';

  # Clean up daily.
  nix.gc = {
    automatic = lib.mkDefault true;
    dates = "*-*-* 05:00:00";
  };
}