{ config, lib, ... }:
{
  sops = {
    templates."atticd.env" = {
      owner = "root";
      group = "root";
      mode = "0400";
      content = ''
        ATTIC_SERVER_TOKEN_RS256_SECRET_BASE64=${config.sops.placeholder."attic/server-token-rs256-secret-base64"}
      '';
    };
  };

  sops.secrets."attic/server-token-rs256-secret-base64" = {
    sopsFile = ../../../../secrets/attic-secrets.yaml;
    owner = "root";
    group = "root";
    mode = "0400";
  };

  # SQLite on disk was the main source of random multi-minute stalls (see attic#113).
  # NAR blobs stay in /var/lib/atticd/storage; only metadata moves to Postgres.
  services.postgresql = {
    enable = true;
    ensureDatabases = [ "atticd" ];
    ensureUsers = [
      {
        name = "atticd";
        ensureDBOwnership = true;
      }
    ];
  };

  services.atticd = {
    enable = true;
    environmentFile = config.sops.templates."atticd.env".path;
    settings = {
      listen = "0.0.0.0:8080";
      jwt = { };
      # Use a libpq socket URI format accepted by Attic's parser.
      database.url = "postgresql:///atticd?host=/run/postgresql&user=atticd";
      chunking = {
        nar-size-threshold = 65536;
        min-size = 16384;
        avg-size = 65536;
        max-size = 262144;
      };
      storage = {
        type = "local";
        path = "/var/lib/atticd/storage";
      };
    };
  };

  systemd.services.atticd = {
    serviceConfig = {
      Restart = lib.mkForce "always";
      RestartSec = lib.mkForce 5;
      # Large closures; default limits can wedge uploads under load.
      LimitNOFILE = 1048576;
    };
  };

  chiasson.system.networking.firewall.allowedTCPPorts = [ 8080 ];
}
