#!/bin/bash
set -e

echo "==== Setting up ArgoCD and Let's Encrypt ClusterIssuer ===="

# Wait for cert-manager to be ready
echo "Waiting for cert-manager webhook to be ready..."
kubectl -n cert-manager wait --for=condition=available --timeout=180s deployment/cert-manager-webhook || true

# Wait for the CRDs to be established
echo "Waiting for cert-manager CRDs to be available..."
for i in $(seq 1 10); do
  echo "Attempt $i to verify cert-manager CRDs..."
  
  if kubectl get crd clusterissuers.cert-manager.io > /dev/null 2>&1; then
    echo "ClusterIssuer CRD found!"
    break
  fi
  
  sleep_time=$((i * 5))
  echo "CRDs not found yet, waiting $sleep_time seconds..."
  sleep $sleep_time
  
  if [ $i -eq 10 ]; then
    echo "Failed to find cert-manager CRDs after multiple attempts"
    exit 1
  fi
done

# Create the ClusterIssuer
echo "Creating Let's Encrypt ClusterIssuer..."
cat > letsencrypt-issuer.yaml << EOF
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
  name: letsencrypt-prod
spec:
  acme:
    email: me@junv.cc
    server: https://acme-v02.api.letsencrypt.org/directory
    privateKeySecretRef:
      name: letsencrypt-prod
    solvers:
    - http01:
        ingress:
          class: nginx
EOF

kubectl apply -f letsencrypt-issuer.yaml

# Verify the ClusterIssuer was created
echo "Verifying ClusterIssuer..."
kubectl get clusterissuer letsencrypt-prod

echo "==== ClusterIssuer setup complete ===="
echo "You can now run 'terraform apply' to continue with the ArgoCD installation"
