#!/bin/bash
# Configure ProviderConfig for Crossplane
# DEPLOY-018: Review and update Proxmox configuration

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

echo "=== Configuring ProviderConfig ==="
echo ""

# Check prerequisites
if ! command -v kubectl &> /dev/null; then
    echo "✗ kubectl is not installed"
    exit 1
fi

if ! kubectl cluster-info &> /dev/null; then
    echo "✗ Cannot connect to Kubernetes cluster"
    exit 1
fi

# Prompt for credentials
echo "Enter Proxmox credentials:"
read -p "Username (default: root@pam): " USERNAME
USERNAME=${USERNAME:-root@pam}

read -sp "Password or API Token: " PASSWORD
echo ""

read -p "Instance 1 Endpoint (default: https://ml110-01.sankofa.nexus:8006): " INSTANCE1_ENDPOINT
INSTANCE1_ENDPOINT=${INSTANCE1_ENDPOINT:-https://ml110-01.sankofa.nexus:8006}

read -p "Instance 2 Endpoint (default: https://r630-01.sankofa.nexus:8006): " INSTANCE2_ENDPOINT
INSTANCE2_ENDPOINT=${INSTANCE2_ENDPOINT:-https://r630-01.sankofa.nexus:8006}

read -p "Skip TLS verification? (y/N): " SKIP_TLS
SKIP_TLS=${SKIP_TLS:-N}

# Create credentials JSON
CREDS_JSON=$(cat <<EOF
{
  "username": "$USERNAME",
  "password": "$PASSWORD"
}
EOF
)

# Create or update secret
echo ""
echo "Creating/updating secret..."
kubectl create secret generic proxmox-credentials \
  --from-literal=credentials.json="$CREDS_JSON" \
  --dry-run=client -o yaml | \
  kubectl apply -n crossplane-system -f -

# Create ProviderConfig
echo ""
echo "Creating ProviderConfig..."
cat <<EOF | kubectl apply -f -
apiVersion: proxmox.sankofa.nexus/v1alpha1
kind: ProviderConfig
metadata:
  name: proxmox-provider-config
  namespace: crossplane-system
spec:
  credentials:
    source: Secret
    secretRef:
      name: proxmox-credentials
      namespace: crossplane-system
      key: credentials.json
  sites:
    - name: us-sfvalley
      endpoint: $INSTANCE1_ENDPOINT
      node: ML110-01
      insecureSkipTLSVerify: $([ "$SKIP_TLS" = "y" ] && echo "true" || echo "false")
    - name: us-sfvalley-2
      endpoint: $INSTANCE2_ENDPOINT
      node: R630-01
      insecureSkipTLSVerify: $([ "$SKIP_TLS" = "y" ] && echo "true" || echo "false")
EOF

echo ""
echo "=== ProviderConfig configured ==="
echo ""
echo "Verify configuration:"
echo "  kubectl get providerconfig proxmox-provider-config -n crossplane-system"
echo "  kubectl describe providerconfig proxmox-provider-config -n crossplane-system"

