# Gitea Initialization Job
# This Job runs after Gitea is installed to create the initial repository
# It uses the same admin credentials from gitea-admin-secret
#
# Apply after Gitea is ready:
#   kubectl apply -f gitea-init-job.yaml -n gitea
#
# To re-run (if needed):
#   kubectl delete job gitea-init-repo -n gitea
#   kubectl apply -f gitea-init-job.yaml -n gitea
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: gitea-init-script
  namespace: gitea
  labels:
    app.kubernetes.io/name: gitea
    app.kubernetes.io/component: init
data:
  init-repo.sh: |
    #!/bin/sh
    set -e

    GITEA_URL="http://gitea-http.gitea.svc.cluster.local:3000"
    REPO_NAME="bakery-ia"
    MAX_RETRIES=30
    RETRY_INTERVAL=10

    echo "=== Gitea Repository Initialization ==="
    echo "Gitea URL: $GITEA_URL"
    echo "Repository: $REPO_NAME"
    echo "Admin User: $GITEA_ADMIN_USER"

    # Wait for Gitea to be ready
    echo ""
    echo "Waiting for Gitea to be ready..."
    RETRIES=0
    until curl -sf "$GITEA_URL/api/v1/version" > /dev/null 2>&1; do
      RETRIES=$((RETRIES + 1))
      if [ $RETRIES -ge $MAX_RETRIES ]; then
        echo "ERROR: Gitea did not become ready after $MAX_RETRIES attempts"
        exit 1
      fi
      echo "  Attempt $RETRIES/$MAX_RETRIES - Gitea not ready, waiting ${RETRY_INTERVAL}s..."
      sleep $RETRY_INTERVAL
    done
    echo "Gitea is ready!"

    # Check if repository already exists
    echo ""
    echo "Checking if repository '$REPO_NAME' exists..."
    HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" \
      -u "$GITEA_ADMIN_USER:$GITEA_ADMIN_PASSWORD" \
      "$GITEA_URL/api/v1/repos/$GITEA_ADMIN_USER/$REPO_NAME")

    if [ "$HTTP_CODE" = "200" ]; then
      echo "Repository '$REPO_NAME' already exists. Nothing to do."
      exit 0
    fi

    # Create the repository
    echo "Creating repository '$REPO_NAME'..."
    RESPONSE=$(curl -s -w "\n%{http_code}" \
      -u "$GITEA_ADMIN_USER:$GITEA_ADMIN_PASSWORD" \
      -X POST "$GITEA_URL/api/v1/user/repos" \
      -H "Content-Type: application/json" \
      -d '{
        "name": "'"$REPO_NAME"'",
        "description": "Main repository for Bakery IA project - Automatically created",
        "private": false,
        "auto_init": true,
        "default_branch": "main",
        "readme": "Default"
      }')

    HTTP_CODE=$(echo "$RESPONSE" | tail -1)
    BODY=$(echo "$RESPONSE" | sed '$d')

    if [ "$HTTP_CODE" = "201" ]; then
      echo "Repository '$REPO_NAME' created successfully!"
      echo ""
      echo "Repository URL: $GITEA_URL/$GITEA_ADMIN_USER/$REPO_NAME"
      echo "Clone URL: $GITEA_URL/$GITEA_ADMIN_USER/$REPO_NAME.git"
    else
      echo "ERROR: Failed to create repository (HTTP $HTTP_CODE)"
      echo "Response: $BODY"
      exit 1
    fi

    # Configure webhook for Tekton (optional - if Tekton is installed)
    echo ""
    echo "Checking if Tekton EventListener is available..."
    TEKTON_URL="http://el-bakery-ia-listener.tekton-pipelines.svc.cluster.local:8080"
    if curl -sf "$TEKTON_URL" > /dev/null 2>&1; then
      echo "Tekton EventListener found. Creating webhook..."
      WEBHOOK_RESPONSE=$(curl -s -w "\n%{http_code}" \
        -u "$GITEA_ADMIN_USER:$GITEA_ADMIN_PASSWORD" \
        -X POST "$GITEA_URL/api/v1/repos/$GITEA_ADMIN_USER/$REPO_NAME/hooks" \
        -H "Content-Type: application/json" \
        -d '{
          "type": "gitea",
          "config": {
            "url": "'"$TEKTON_URL"'",
            "content_type": "json"
          },
          "events": ["push"],
          "active": true
        }')

      WEBHOOK_CODE=$(echo "$WEBHOOK_RESPONSE" | tail -1)
      if [ "$WEBHOOK_CODE" = "201" ]; then
        echo "Webhook created successfully!"
      else
        echo "Warning: Could not create webhook (HTTP $WEBHOOK_CODE). You may need to configure it manually."
      fi
    else
      echo "Tekton EventListener not available. Skipping webhook creation."
    fi

    echo ""
    echo "=== Initialization Complete ==="
---
apiVersion: batch/v1
kind: Job
metadata:
  name: gitea-init-repo
  namespace: gitea
  labels:
    app.kubernetes.io/name: gitea
    app.kubernetes.io/component: init
  annotations:
    # Helm hook annotations (if used with Helm)
    helm.sh/hook: post-install,post-upgrade
    helm.sh/hook-weight: "10"
    helm.sh/hook-delete-policy: before-hook-creation
spec:
  ttlSecondsAfterFinished: 300
  backoffLimit: 3
  template:
    metadata:
      labels:
        app.kubernetes.io/name: gitea
        app.kubernetes.io/component: init
    spec:
      restartPolicy: OnFailure
      containers:
        - name: init-repo
          image: curlimages/curl:8.5.0
          command: ["/bin/sh", "/scripts/init-repo.sh"]
          env:
            - name: GITEA_ADMIN_USER
              valueFrom:
                secretKeyRef:
                  name: gitea-admin-secret
                  key: username
            - name: GITEA_ADMIN_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: gitea-admin-secret
                  key: password
          volumeMounts:
            - name: init-script
              mountPath: /scripts
          resources:
            limits:
              cpu: 100m
              memory: 64Mi
            requests:
              cpu: 50m
              memory: 32Mi
      volumes:
        - name: init-script
          configMap:
            name: gitea-init-script
            defaultMode: 0755
