# Wait-for-databases Job - ensures Database CRs are reconciled before apps start
# This solves the race condition where Forgejo starts before CNPG creates the database
apiVersion: batch/v1
kind: Job
metadata:
  name: wait-for-databases
  namespace: ddb
  annotations:
    description: "Waits for CNPG to reconcile Database CRs and create databases in PostgreSQL"
spec:
  backoffLimit: 5
  template:
    metadata:
      name: wait-for-databases
    spec:
      restartPolicy: Never
      serviceAccountName: wait-for-databases
      containers:
      - name: wait
        image: bitnami/kubectl:latest
        command:
        - /bin/bash
        - -c
        - |
          set -euo pipefail
          
          echo "==> Waiting for CNPG Database CRs to be reconciled..."
          
          DATABASES="forgejo authentik temporal temporal-visibility"
          
          for db in $DATABASES; do
            echo "Checking database: $db"
            
            for i in {1..60}; do
              # Check if Database CR exists and is ready
              READY=$(kubectl get database $db -n ddb -o jsonpath='{.status.ready}' 2>/dev/null || echo "false")
              
              if [ "$READY" = "true" ]; then
                echo "  ✓ $db is ready"
                break
              fi
              
              echo "  Waiting for $db to be ready... ($i/60)"
              sleep 5
              
              if [ $i -eq 60 ]; then
                echo "  ✗ Timeout waiting for $db"
                exit 1
              fi
            done
          done
          
          echo ""
          echo "==> All databases are ready!"
          echo "CNPG has created the following databases:"
          kubectl get databases -n ddb
          
          echo ""
          echo "✅ Safe to deploy applications now"
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: wait-for-databases
  namespace: ddb
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: wait-for-databases
  namespace: ddb
rules:
- apiGroups: ["postgresql.cnpg.io"]
  resources: ["databases"]
  verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: wait-for-databases
  namespace: ddb
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: wait-for-databases
subjects:
- kind: ServiceAccount
  name: wait-for-databases
  namespace: ddb
