{ self, config, lib, pkgs, ... }:

{
  age.secrets.gitea-dbpass.file = "${self}/secrets/gitea-dbpass.age";
  age.secrets.gitea-dbpass.owner = "gitea";

  services.forgejo = {
    enable = true;
    user = "gitea";
    group = "gitea";
    stateDir = "/var/lib/gitea";
    database = {
      type = "postgres";
      user = "gitea";
      name = "gitea";
      passwordFile = "/run/agenix/gitea-dbpass";
    };
    settings = {
      DEFAULT.APP_NAME = "Sealight Git Forge";
      server = {
        DOMAIN = "git.sealight.xyz";
        ROOT_URL = "https://git.sealight.xyz";
        HTTP_PORT = 3001;
      };
      metrics = {
        ENABLED = true;
      };
      repository = {
        DEFAULT_BRANCH = "main";
      };
      service.DISABLE_REGISTRATION = true;
      "markup.restructuredtext" = {
        ENABLED = true;
        FILE_EXTENSIONS = ".rst";
        RENDER_COMMAND = "timeout 30s pandoc +RTS -RTS -f rst";
        IS_INPUT_FILE = false;
      };
      mailer = {
        ENABLED = true;
        MAILER_TYPE = "smtp";
        FROM = "ops@sealight.xyz";
        SMTP_ADDR = "smtp.nullhex.com";
        SMTP_PORT = "465";
        USER = "ops@sealight.xyz";
        PASSWD = "breed deputy fossil glory"; # TODO how do we pass this from agenix?
        IS_TLS_ENABLED = "true";
      };
    };
  };

  users.users.gitea = {
    home = "/var/lib/gitea";
    useDefaultShell = true;
    group = "gitea";
    isSystemUser = true;
  };

  users.groups.gitea = {};

  environment.systemPackages = [ pkgs.pandoc ];
  services.postgresql = {
    enable = true; # Ensure postgresql is enabled
    # authentication = ''
    #   local gitea all ident map=gitea-users
    # '';
    # identMap = # Map the gitea user to postgresql
    #   ''
    #     gitea-users gitea gitea
    #     gitea-users postgres gitea
    #   '';
    ensureDatabases = [ "gitea" ];
    ensureUsers = [{ 
      name = "gitea"; 
      ensureDBOwnership = true; 
    }];
    # TODO
    # initialScript 
    # set password for gitea user
  };

  services.nginx = {
    enable = true; # Enable Nginx
    recommendedGzipSettings = true;
    recommendedOptimisation = true;
    recommendedProxySettings = true;
    recommendedTlsSettings = true;
    virtualHosts."git.sealight.xyz" = {
      # Gitea hostname
      enableACME = true; # Use ACME certs
      forceSSL = true; # Force SSL
      locations."/".proxyPass = "http://localhost:3001/"; # Proxy Gitea
    };
  };
  networking.firewall.allowedTCPPorts = [ 80 443 22 ];
}
