/*
A nix cache for our use


atticd-atticadm make-token --sub "admin_username" --validity "10y" --pull "*" --push "*" --create-cache "*" --delete "*" --configure-cache "*" --configure-cache-retention "*" --destroy-cache "*"

# for the gitlab runner, done eyarly
atticd-atticadm make-token --sub "wheatly-runner" --validity "1y" --pull "skynet-cache" --push "skynet-cache"


Documentation:
https://docs.attic.rs/introduction.html
*/
{
  lib,
  config,
  pkgs,
  inputs,
  ...
}:
with lib; let
  name = "nix-cache";
  cfg = config.services.skynet."${name}";
in {
  imports = [
    inputs.attic.nixosModules.atticd
  ];

  options.services.skynet."${name}" = {
    enable = mkEnableOption "Skynet Nix Cache";
  };

  config = mkIf cfg.enable {
    services.skynet.acme.domains = [
      "${name}.skynet.ie"
    ];

    services.skynet.dns.records = [
      {
        record = "${name}";
        r_type = "CNAME";
        value = config.services.skynet.host.name;
      }
    ];

    users.groups."nix-serve" = {};
    users.users."nix-serve" = {
      isSystemUser = true;
      group = "nix-serve";
    };

    services.atticd = {
      enable = true;

      # Replace with absolute path to your credentials file
      credentialsFile = "/etc/atticd.env";

      settings = {
        listen = "127.0.0.1:8080";

        # Data chunking
        #
        # Warning: If you change any of the values here, it will be
        # difficult to reuse existing chunks for newly-uploaded NARs
        # since the cutpoints will be different. As a result, the
        # deduplication ratio will suffer for a while after the change.
        chunking = {
          # The minimum NAR size to trigger chunking
          #
          # If 0, chunking is disabled entirely for newly-uploaded NARs.
          # If 1, all NARs are chunked.
          nar-size-threshold = 64 * 1024; # 64 KiB

          # The preferred minimum size of a chunk, in bytes
          min-size = 16 * 1024; # 16 KiB

          # The preferred average size of a chunk, in bytes
          avg-size = 64 * 1024; # 64 KiB

          # The preferred maximum size of a chunk, in bytes
          max-size = 256 * 1024; # 256 KiB
        };
      };
    };

    networking.firewall.allowedTCPPorts = [80 443];
    services.nginx = {
      clientMaxBodySize = "500m";
      virtualHosts = {
        "${name}.skynet.ie" = {
          forceSSL = true;
          useACMEHost = "skynet";
          locations."/" = {
            proxyPass = "http://127.0.0.1:8080";
          };
        };
      };
    };
  };
}