#!/bin/bash

echo "🔧 Fixing Forgejo issues..."
echo ""

# Issue 1: Multi-Attach - old pod still holding the volume
echo "==> Issue 1: Cleaning up old Forgejo deployment"
echo "Current deployments:"
kubectl get deployment -n cicd | grep forgejo

echo ""
OLD_DEPLOYMENT=$(kubectl get deployment -n cicd -o name | grep -E "forgejo-[0-9]" | grep -v gitea)
if [ -n "$OLD_DEPLOYMENT" ]; then
    echo "Found old deployment: $OLD_DEPLOYMENT"
    kubectl delete $OLD_DEPLOYMENT -n cicd --wait=true
    echo "  ✓ Old deployment deleted"
else
    echo "  No old deployment found, checking for orphaned pods..."
    kubectl get pods -n cicd -l app.kubernetes.io/name=gitea -o name | while read pod; do
        POD_NAME=$(echo $pod | cut -d/ -f2)
        if [[ ! "$POD_NAME" =~ "forgejo-gitea" ]]; then
            echo "  Deleting orphaned pod: $POD_NAME"
            kubectl delete pod -n cicd $POD_NAME --force --grace-period=0
        fi
    done
fi

# Issue 2: Missing homelab-ca ConfigMap
echo ""
echo "==> Issue 2: Checking homelab-ca ConfigMap"
if kubectl get configmap homelab-ca -n cicd &>/dev/null; then
    echo "  ✓ homelab-ca already exists"
else
    echo "  ⚠️  homelab-ca not found in cicd namespace"
    echo "  Checking if it exists elsewhere..."
    
    # Check common namespaces
    for ns in default kube-system cert-manager; do
        if kubectl get configmap homelab-ca -n $ns &>/dev/null; then
            echo "  Found in namespace: $ns"
            echo "  Copying to cicd namespace..."
            kubectl get configmap homelab-ca -n $ns -o yaml | \
                sed 's/namespace: '$ns'/namespace: cicd/' | \
                kubectl apply -f -
            echo "  ✓ Copied homelab-ca to cicd"
            break
        fi
    done
    
    # If still not found, check if we need to create it
    if ! kubectl get configmap homelab-ca -n cicd &>/dev/null; then
        echo "  Creating empty homelab-ca ConfigMap (you may need to populate it)..."
        kubectl create configmap homelab-ca -n cicd --from-literal=ca.crt=""
        echo "  ⚠️  Created empty ConfigMap - update with actual CA if needed"
    fi
fi

echo ""
echo "==> Waiting for volume detach (30s)..."
sleep 30

echo ""
echo "==> Current Forgejo pod status:"
kubectl get pods -n cicd -l app.kubernetes.io/name=gitea

echo ""
echo "==> If still in Init or Pending, describe one pod:"
POD=$(kubectl get pods -n cicd -l app.kubernetes.io/name=gitea --no-headers | head -1 | awk '{print $1}')
if [ -n "$POD" ]; then
    kubectl describe pod -n cicd $POD | grep -A 10 "Events:" | head -15
fi

echo ""
echo "✅ Fixes applied!"
echo ""
echo "Next: Monitor pod startup"
echo "  kubectl get pods -n cicd -w"
