# PostSync hook to register Authentik as OAuth login source in Forgejo
apiVersion: batch/v1
kind: Job
metadata:
  name: forgejo-oauth-setup
  namespace: cicd
  annotations:
    argocd.argoproj.io/hook: PostSync
    argocd.argoproj.io/hook-delete-policy: BeforeHookCreation
spec:
  backoffLimit: 3
  template:
    spec:
      restartPolicy: Never
      serviceAccountName: forgejo-oauth-setup
      containers:
      - name: setup
        image: python:3.12-alpine
        command:
        - /bin/sh
        - -c
        - |
          set -e
          
          # Download kubectl
          echo "Installing kubectl..."
          wget -q -O /tmp/kubectl https://dl.k8s.io/release/v1.28.0/bin/linux/amd64/kubectl
          chmod +x /tmp/kubectl
          export PATH=/tmp:$PATH
          
          echo "Waiting for Forgejo to be ready..."
          for i in {1..30}; do
            if wget -q -O- http://forgejo-gitea-http.cicd.svc:3000/api/healthz 2>/dev/null; then
              echo "Forgejo is ready"
              break
            fi
            echo "  Waiting... ($i/30)"
            sleep 5
          done
          
          # Get admin credentials
          ADMIN_USER=$(kubectl -n cicd get secret forgejo-admin-secret -o jsonpath='{.data.username}' 2>/dev/null | base64 -d || echo "rock")
          ADMIN_PASS=$(kubectl -n cicd get secret forgejo-admin-secret -o jsonpath='{.data.password}' 2>/dev/null | base64 -d || echo "")
          
          if [ -z "$ADMIN_PASS" ]; then
            echo "ERROR: No admin password found. Cannot configure OAuth."
            exit 1
          fi
          
          # Get OAuth credentials
          CLIENT_SECRET=$(kubectl -n cicd get secret forgejo-oidc -o jsonpath='{.data.CLIENT_SECRET}' | base64 -d)
          
          echo "Checking if OAuth source already exists..."
          SOURCES=$(wget -q -O- \
            --header="Content-Type: application/json" \
            --user="$ADMIN_USER:$ADMIN_PASS" \
            http://forgejo-gitea-http.cicd.svc:3000/api/v1/admin/auth)
          
          if echo "$SOURCES" | grep -q "authentik"; then
            echo "OAuth source 'authentik' already exists"
            exit 0
          fi
          
          echo "Creating OAuth authentication source..."
          wget -q -O- \
            --header="Content-Type: application/json" \
            --user="$ADMIN_USER:$ADMIN_PASS" \
            --post-data='{
              "type": "oauth2",
              "name": "authentik",
              "is_active": true,
              "oauth2_provider": "openidConnect",
              "client_id": "forgejo",
              "client_secret": "'"$CLIENT_SECRET"'",
              "openid_connect_auto_discovery_url": "https://authentik.riotpiao.com/application/o/forgejo/.well-known/openid-configuration",
              "scopes": ["openid", "profile", "email", "groups"]
            }' \
            http://forgejo-gitea-http.cicd.svc:3000/api/v1/admin/auth
          
          echo
          echo "OAuth source configured successfully"
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: forgejo-oauth-setup
  namespace: cicd
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: forgejo-oauth-setup
  namespace: cicd
rules:
- apiGroups: [""]
  resources: ["secrets"]
  verbs: ["get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: forgejo-oauth-setup
  namespace: cicd
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: forgejo-oauth-setup
subjects:
- kind: ServiceAccount
  name: forgejo-oauth-setup
  namespace: cicd
