{
  lib,
  self,
  config,
  ...
}:
let
  inherit (lib.modules) mkIf;
  inherit (self.lib) mkServiceOption mkSecret;

  rdomain = config.networking.domain;

  cfg = config.garden.services.attic;
in
{
  options.garden.services.attic = mkServiceOption "attic" {
    domain = "cache.${rdomain}";
    host = "[::]";
    port = 3003;
  };

  config = mkIf config.garden.services.attic.enable {
    sops.secrets.attic-env = mkSecret {
      file = "attic";
      key = "env";
    };

    services = {
      atticd = {
        enable = true;
        environmentFile = config.sops.secrets.attic-env.path;

        settings = {
          listen = "${cfg.host}:${toString cfg.port}";

          storage = {
            bucket = "tgc-nix-cache";
            type = "s3";
            region = "auto";
            endpoint = "https://190n4.upcloudobjects.com";
          };

          chunking = {
            nar-size-threshold = 65536;
            min-size = 16384;
            avg-size = 65536;
            max-size = 262144;
          };

          compression = {
            type = "zstd";
            level = 12;
          };

          garbage-collection.interval = "8 hours";
        };
      };

      nginx.virtualHosts.${cfg.domain} = {
        locations."/" = {
          proxyPass = "http://${cfg.host}:${toString cfg.port}";
          extraConfig = ''
            client_max_body_size 1G;
          '';
        };
      };
    };
  };
}
