{ config, containerCfg, pkgs, lib, builder, name, ... }:
let 
  version = "latest";
  serverCfg = config.syscfg.server;

  LDAP_DC_DOMAIN = "dc=ldap," + (lib.concatMapStringsSep "," (x: "dc=${x}") (lib.splitString "." serverCfg.domain));
in {
  requires = {
    secrets = [ name ];
    databases = [ name ];
  };

  runtime = {
    paths = [{
      path="${serverCfg.path.data.path}/gitea";
      owner = "1000:1000";
      dirs = ["data" "runner"];
      mode = "0755";
    }];
    containers = {
      server = builder.mkContainer {
        subdomain = containerCfg.subdomain;
        image = "gitea/gitea:${version}";
        port = 8080;
        secret = name;
        
        extraEnv = { # app.ini -> GITEA__<section>__<KEY> = "<VALUE>";
          GITEA__DEFAULT__APP_NAME = if(containerCfg.extra ? name) then containerCfg.extra.name else "Gitea";
          GITEA__repository__DISABLED_REPO_UNITS = "repo.ext_issues,repo.ext_wiki";
          GITEA__repository__DISABLE_STARS = "true";
          GITEA__repository__DEFAULT_MERGE_STYLE = "squash";
          # GITEA__ui__THEMES = "";
          # GITEA__ui__DEFAULT_THEME = "";

          # GITEA__security__SECRET_KEY = "SECRET_ENV";
          # GITEA__security__INTERNAL_TOKEN = "SECRET_ENV";
          # GITEA__database__PASSWD = "SECRET_ENV";
          # GITEA__mailer__PASSWD="SECRET_ENV";

          GITEA__database__DB_TYPE = "postgres"; 
          GITEA__database__HOST = builder.host;
          GITEA__database__NAME = "gitea_db";
          GITEA__database__USER = "gitea_user";


          GITEA__mailer__ENABLED = "true";
          GITEA__mailer__FROM = "";
          GITEA__mailer__PROTOCOL = "smtps";
          GITEA__mailer__SMTP_ADDR = "";
          GITEA__mailer__SMTP_PORT = "";
          GITEA__mailer__USER= "";

          GITEA__server__DOMAIN = "${containerCfg.subdomain}.${serverCfg.domain}";
          GITEA__server__ROOT_URL = "https://${containerCfg.subdomain}.${serverCfg.domain}/";
          GITEA__server__PROTOCOL = "http";
          GITEA__server__HTTP_PORT = "8080";
          GITEA__server__LFS_START_SERVER = "true";
          GITEA__security__INSTALL_LOCK = "true";

        } // ( if serverCfg.containers?authentik then {
          GITEA__service__ENABLE_BASIC_AUTHENTICATION = "false";
          GITEA__service__ENABLE_REVERSE_PROXY_AUTHENTICATION = "true";
          GITEA__service__ENABLE_REVERSE_PROXY_AUTHENTICATION_API = "true";
          GITEA__service__ENABLE_REVERSE_PROXY_AUTO_REGISTRATION = "true";
          GITEA__service__ENABLE_REVERSE_PROXY_EMAIL = "true";
          GITEA__service__ENABLE_REVERSE_PROXY_FULL_NAME = "true";
          GITEA__service__ALLOW_ONLY_EXTERNAL_REGISTRATION = "true";
          GITEA__security__REVERSE_PROXY_LOGOUT_REDIRECT = "https://${serverCfg.containers.authentik.subdomain}.${serverCfg.domain}/outpost.goauthentik.io/sign_out";
          GITEA__security__REVERSE_PROXY_AUTHENTICATION_USER = "X-authentik-username";
          GITEA__security__REVERSE_PROXY_AUTHENTICATION_EMAIL = "X-authentik-email";
          GITEA__security__REVERSE_PROXY_AUTHENTICATION_FULL_NAME = "X-authentik-name";
          GITEA__security__RREVERSE_PROXY_LIMIT = "1";
          GITEA__security__REVERSE_PROXY_TRUSTED_PROXIES = "127.0.0.0/8,::1/128,10.0.0.0/8";
        } else {});
        extraLabels = {
          "traefik.http.routers.${containerCfg.subdomain}-login.rule" = "Host(`${containerCfg.subdomain}.${serverCfg.domain}`) && Path(`/user/login`) ";
          "traefik.http.routers.${containerCfg.subdomain}-login.middlewares" = if (serverCfg.containers?authentik && containerCfg.extra?proxyauth) then "authentik" else "";
          "traefik.http.routers.${containerCfg.subdomain}-login.priority" = "100";
          "traefik.http.routers.${containerCfg.subdomain}-login.entrypoints" = "web-secure";
          "traefik.http.routers.${containerCfg.subdomain}-login.tls" = "true";
        };

        overrides = {
          volumes = [
            "${serverCfg.path.data.path}/gitea/data:/data"
          ];
          ports = [ "2222:22" ]; 
        };
      };

      runner = builder.mkContainer {
        image = "gitea/act_runner:${version}";
        secret = name;
        extraEnv = { 
          #CONFIG_FILE="/data/config.yml";
          GITEA_INSTANCE_URL="https://${containerCfg.subdomain}.${serverCfg.domain}";
          GITHUB_INSTANCE_URL="https://${containerCfg.subdomain}.${serverCfg.domain}";
        };

        overrides = {
          volumes = [
            "${serverCfg.path.data.path}/gitea/runner:/data"
            "/var/run/podman/podman.sock:/var/run/docker.sock"
          ];
        };
      };
    };


    setup = {
      trigger = "server";
      envFile = config.sops.secrets."CUSTOM".path;
      script = pkgs.writeShellScript "setup" ''
        # Define the command wrapper
        GT="${pkgs.podman}/bin/podman --events-backend=none exec -u git gitea-server gitea"
        GTR="${pkgs.podman}/bin/podman --events-backend=none exec -u git gitea-runner ./act_runner"

        $GT admin user create --username "$DEFAULT_ADMIN_USERNAME" --password "$DEFAULT_ADMIN_PASSWORD" --email "$DEFAULT_ADMIN_EMAIL" --admin || true

        touch ${serverCfg.path.data.path}/gitea/data-runner/config.yml

        RUNNER_TOKEN=$($GT actions generate-runner-token)
        $GTR register \
          --instance "https://${containerCfg.subdomain}.${serverCfg.domain}" \
          --token "$RUNNER_TOKEN" \
          --name "Runner" \
          --labels "ubuntu-latest:docker://catthehacker/ubuntu:act-latest" \
          --no-interactive


        ${lib.optionalString (serverCfg.containers ? authentik) ''
        $GT admin auth add-ldap --name Authentik --host authentik-ldap --port 6636 --security-protocol ldaps --skip-tls-verify \
            --bind-dn "cn=ldap-service,ou=users,${LDAP_DC_DOMAIN}" --bind-password $DEFAULT_LDAP_PASSWORD \
            --user-search-base "ou=users,${LDAP_DC_DOMAIN}" \
            --user-filter "(&(objectClass=user)(|(uid=%[1]s)(mail=%[1]s)))" \
            --admin-filter "(memberOf=cn=admin,ou=groups,${LDAP_DC_DOMAIN})" \
            --username-attribute "username" --firstname-attribute "givenName" --surname-attribute "sn" --email-attribute "mail" \
            --synchronize-users
        ''}

        echo "Completed Gitea Setup"
      '';
    };
  };
}
