{
  pkgs,
  lib,
  config,
  ...
}:
let
  setApp = pkgs.writeShellApplication {
    name = "forgejo-set-oauth-app";
    runtimeInputs = [
      pkgs.forgejo
      pkgs.gnugrep
    ];
    text = ''
      config="${config.services.forgejo.stateDir}/custom/conf/app.ini"
      secret="$(cat ${config.khscodes.infrastructure.kanidm-client-application.secretFile})"

      options=(
          "--name" "Kanidm" \
          "--key" "forgejo" \
          "--secret" "$secret" \
          "--auto-discover-url" https://login.kaareskovgaard.net/oauth2/openid/forgejo/.well-known/openid-configuration \
          "--scopes" "email profile" \
          "--skip-local-2fa" \
          "--provider" openidConnect \
          "--group-claim-name" "groups" \
          "--admin-group" "admin" \
          "--group-team-map-removal" \
          "--group-team-map" '{"nix": {"nix": [] }, "actions": { "actons": [] }}'
      )

      if gitea "--config=$config" admin auth list | grep -q "Kanidm" 2> /dev/null; then
        id="$(gitea "--config=$config" admin auth list | grep "Kanidm" | cut -d$'\t' -f1)"
        gitea "--config=$config" admin auth update-oauth \
          --id "$id" \
          "''${options[@]}"
      else
        gitea "--config=$config" admin auth add-oauth \
          "''${options[@]}"
      fi
    '';
  };
in
{
  khscodes.infrastructure.kanidm-client-application = {
    enable = true;
    appName = "forgejo";
    secretOwner = "git";
    restartUnits = [ "forgejo-setup-oauth.service" ];
  };
  systemd.services.forgejo-setup-oauth = {
    enable = true;
    wants = [ "vault-agent-openbao.service" ];
    requires = [ "forgejo.service" ];
    after = [
      "forgejo.service"
      "vault-agent-openbao.service"
    ];
    unitConfig = {
      ConditionPathExists = [ config.khscodes.infrastructure.kanidm-client-application.secretFile ];
    };
    serviceConfig = {
      Type = "oneshot";
      User = "git";
      Group = "git";
      ExecStart = lib.getExe setApp;
    };
  };
}
