#!/bin/bash
# create-proxmox-secret.sh
# Creates Kubernetes secret for Proxmox credentials

set -euo pipefail

# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m'

# Configuration
NAMESPACE="${NAMESPACE:-crossplane-system}"
SECRET_NAME="${SECRET_NAME:-proxmox-credentials}"
KEY_NAME="${KEY_NAME:-credentials.json}"

log() {
    echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $1"
}

error() {
    echo -e "${RED}[ERROR]${NC} $1" >&2
    exit 1
}

warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

check_prerequisites() {
    if ! command -v kubectl &> /dev/null; then
        error "kubectl is required but not installed"
    fi
    
    if ! kubectl cluster-info &> /dev/null; then
        error "Cannot connect to Kubernetes cluster"
    fi
}

prompt_credentials() {
    echo ""
    echo "Enter Proxmox credentials:"
    echo ""
    
    read -p "Username (e.g., root@pam): " USERNAME
    read -sp "Token (format: user@realm!token-id=token-secret): " TOKEN
    echo ""
    
    if [ -z "$USERNAME" ] || [ -z "$TOKEN" ]; then
        error "Username and token are required"
    fi
    
    CREDENTIALS_JSON=$(cat <<EOF
{
  "username": "${USERNAME}",
  "token": "${TOKEN}"
}
EOF
)
}

create_secret() {
    log "Creating Kubernetes secret: ${SECRET_NAME} in namespace ${NAMESPACE}"
    
    # Create namespace if it doesn't exist
    kubectl create namespace "${NAMESPACE}" --dry-run=client -o yaml | kubectl apply -f -
    
    # Check if secret already exists
    if kubectl get secret "${SECRET_NAME}" -n "${NAMESPACE}" &> /dev/null; then
        warn "Secret ${SECRET_NAME} already exists in namespace ${NAMESPACE}"
        read -p "Do you want to update it? (y/N): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            log "Skipping secret creation"
            return 0
        fi
        kubectl delete secret "${SECRET_NAME}" -n "${NAMESPACE}"
    fi
    
    # Create secret
    echo "${CREDENTIALS_JSON}" | kubectl create secret generic "${SECRET_NAME}" \
        --from-file="${KEY_NAME}=/dev/stdin" \
        -n "${NAMESPACE}" \
        --dry-run=client -o yaml | kubectl apply -f -
    
    log "✓ Secret created successfully"
}

verify_secret() {
    log "Verifying secret..."
    
    if kubectl get secret "${SECRET_NAME}" -n "${NAMESPACE}" &> /dev/null; then
        log "✓ Secret exists"
        
        # Show secret metadata (not the actual content)
        kubectl get secret "${SECRET_NAME}" -n "${NAMESPACE}" -o jsonpath='{.metadata.name}' | xargs echo "  Name:"
        kubectl get secret "${SECRET_NAME}" -n "${NAMESPACE}" -o jsonpath='{.data}' | jq -r 'keys[]' | while read key; do
            echo "  Key: ${key}"
        done
    else
        error "Secret verification failed"
    fi
}

main() {
    log "Proxmox Credentials Secret Creator"
    log "=================================="
    
    check_prerequisites
    prompt_credentials
    create_secret
    verify_secret
    
    log ""
    log "Secret created successfully!"
    log ""
    log "Next steps:"
    log "1. Apply ProviderConfig: kubectl apply -f crossplane-provider-proxmox/examples/provider-config.yaml"
    log "2. Verify ProviderConfig status: kubectl get providerconfig proxmox-provider-config"
    log "3. Check provider logs: kubectl logs -n crossplane-system -l app=crossplane-provider-proxmox"
}

main "$@"

