{ config, ... }:

{
  system.stateVersion = "22.05";

  c3d2 = {
    deployment.server = "server10";
    hq.statistics.enable = true;
  };
  microvm = {
    vcpu = 8;
    mem = 12 * 1024;
  };

  networking = {
    hostName = "caveman";
    firewall.allowedTCPPorts = [
      # telnet
      23
      # redis
      6379
    ];
  };

  services.journald.extraConfig = ''
    Storage=volatile
  '';

  sops = {
    defaultSopsFile = ./secrets.yaml;
    secrets = {
      "redis/caveman/requirePass".mode = "0444";
      # Must be readable for DynamicUser caveman-sieve
      "caveman/sieve/privKey".mode = "0444";
    };
  };

  services = {
    redis.servers.caveman = {
      # Listen on the public network
      bind = null;
      # Override default backup schedule to reduce I/O
      save = [
        # Every 2h if at least 1 entry changed
        [ 7200 1 ]
        # Every 30min if at least 10000 entries changed
        [ 1800 10000 ]
      ];
    };

    caveman = {
      redis = {
        # leave 4 GB for caveman services
        maxmemory = (config.microvm.mem - 4) * 1024 * 1024;
        passwordFile = config.sops.secrets."redis/caveman/requirePass".path;
      };

      hunter = {
        enable = true;
        settings = {
          prometheus_port = 9103;
          max_workers = 384;
          hosts = with builtins;
            filter (line: isString line && line != "") (
              split "\n" (
                readFile ./mastodon-instances.txt
              )
            );
        };
      };
      sieve = {
        enable = true;
        settings.priv_key_file = config.sops.secrets."caveman/sieve/privKey".path;
      };
      butcher.enable = true;
      gatherer.enable = true;
      smokestack.enable = true;
    };

    nginx = {
      enable = true;
      virtualHosts."fedi.buzz" = {
        default = true;
        forceSSL = true;
        enableACME = true;
        serverAliases = [
          "www.fedi.buzz"
          "caveman.flpk.zentralwerk.org"
        ];
        locations."/".proxyPass = "http://127.0.0.1:${toString config.services.caveman.gatherer.settings.listen_port}/";
      };
    };
  };
}
