{ config, lib, ... }:
let
  cfg = config.services.forgejo;
  srv = cfg.settings.server;
in
{
  services.forgejo = {
    enable = true;

    database = {
      type = "postgres";
      host = "db-01.tailnet.escapeangle.com";
      createDatabase = false;
    };

    lfs.enable = true;

    settings = {
      server = {
        DOMAIN = "git.escapeangle.com";
        ROOT_URL = "https://${srv.DOMAIN}";
        HTTP_PORT = 3000;
        LANDING_PAGE = "explore";
      };

      ui.DEFAULT_THEME = "gitea-auto";

      service = {
        DISABLE_REGISTRATION = false;
        ALLOW_ONLY_EXTERNAL_REGISTRATION = true;
        SHOW_REGISTRATION_BUTTON = false;
      };

      openid = {
        ENABLE_OPENID_SIGNIN = false;
        ENABLE_OPENID_SIGNUP = true;
        WHITELISTED_URIS = "auth.escapeangle.com";
      };

      storage = {
        STORAGE_TYPE = "minio";
        MINIO_ENDPOINT = "daf6ae2391d4d68ecf3c5af2f1540f5c.r2.cloudflarestorage.com";
        MINIO_BUCKET = "forgejo";
        MINIO_LOCATION = "auto";
        MINIO_USE_SSL = true;
        MINIO_CHECKSUM_ALGORITHM = "md5";
      };

      mailer = {
        ENABLED = true;
        SMTP_ADDR = "mail.escapeangle.com";
        FROM = "forgejo@escapeangle.com";
        USER = "forgejo@escapeangle.com";
      };
    };

    secrets = {
      storage = {
        MINIO_ACCESS_KEY_ID = config.sops.secrets."forgejo/access-key-id".path;
        MINIO_SECRET_ACCESS_KEY = config.sops.secrets."forgejo/secret-access-key".path;
      };

      mailer = {
        PASSWD = config.sops.secrets."forgejo/mailer-password".path;
      };
    };
  };

  systemd.services.forgejo = {
    requires = [ "tailscaled.service" ];

    preStart = # bash
      ''
        auth="${lib.getExe config.services.forgejo.package} admin auth"

        echo "Trying to find existing sso configuration for Authelia"...
        set +e -o pipefail
        id="$($auth list | grep "Authelia.*OAuth2" |  cut -d'	' -f1)"
        found=$?
        set -e +o pipefail

        if [[ $found = 0 ]]; then
          echo Found sso configuration at id=$id, updating it if needed.
          $auth update-oauth \
            --id       $id \
            --name     "Authelia" \
            --provider openidConnect \
            --key      forgejo \
            --secret   $(tr -d '\n' < ${config.sops.secrets."forgejo/oidc-secret".path}) \
            --auto-discover-url https://auth.escapeangle.com/.well-known/openid-configuration
        else
          echo Did not find any sso configuration, creating one with name Authelia.
          $auth add-oauth \
            --name     Authelia \
            --provider openidConnect \
            --key      forgejo \
            --secret   $(tr -d '\n' < ${config.sops.secrets."forgejo/oidc-secret".path}) \
            --auto-discover-url https://auth.escapeangle.com/.well-known/openid-configuration
        fi
      '';
  };

  services.nginx.virtualHosts."git.escapeangle.com" = {
    forceSSL = true;
    enableACME = true;
    extraConfig = ''
      client_max_body_size 512M;
    '';
    locations."/" = {
      proxyPass = "http://localhost:${toString srv.HTTP_PORT}";
    };
  };

  sops = {
    defaultSopsFile = ../hosting-01.yaml;
    secrets = {
      "forgejo/mailer-password" = {
        owner = "forgejo";
      };
      "forgejo/oidc-secret" = {
        owner = "forgejo";
      };
      "forgejo/access-key-id" = {
        owner = "forgejo";
      };
      "forgejo/secret-access-key" = {
        owner = "forgejo";
      };
    };
  };
}
