#!/bin/bash
set -euo pipefail

# Deploy Proxmox Crossplane Provider Script
# This script deploys the Crossplane provider to Kubernetes

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
PROVIDER_DIR="${PROJECT_ROOT}/crossplane-provider-proxmox"

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

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

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

log_warning() {
    echo -e "${YELLOW}[$(date +'%Y-%m-%d %H:%M:%S')] ⚠️${NC} $*"
}

log_error() {
    echo -e "${RED}[$(date +'%Y-%m-%d %H:%M:%S')] ❌${NC} $*"
}

error() {
    log_error "$*"
    exit 1
}

check_prerequisites() {
    log "Checking 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
    
    log_success "Prerequisites check passed"
}

deploy_crds() {
    log "Deploying CRDs..."
    
    CRD_DIR="${PROVIDER_DIR}/config/crd/bases"
    
    if [ ! -d "${CRD_DIR}" ]; then
        log_warning "CRD directory not found, generating CRDs..."
        if [ -f "${PROVIDER_DIR}/Makefile" ]; then
            cd "${PROVIDER_DIR}"
            if command -v make &> /dev/null; then
                make manifests || log_warning "Failed to generate CRDs with make"
            fi
        fi
    fi
    
    if [ -d "${CRD_DIR}" ] && [ "$(ls -A ${CRD_DIR}/*.yaml 2>/dev/null)" ]; then
        kubectl apply -f "${CRD_DIR}" || error "Failed to apply CRDs"
        log_success "CRDs deployed"
    else
        log_warning "No CRD files found, skipping CRD deployment"
        log "Note: CRDs may need to be generated first with 'make manifests'"
    fi
}

deploy_provider() {
    log "Deploying provider..."
    
    PROVIDER_MANIFEST="${PROVIDER_DIR}/config/provider.yaml"
    
    if [ ! -f "${PROVIDER_MANIFEST}" ]; then
        error "Provider manifest not found: ${PROVIDER_MANIFEST}"
    fi
    
    kubectl apply -f "${PROVIDER_MANIFEST}" || error "Failed to deploy provider"
    log_success "Provider deployed"
}

wait_for_provider() {
    log "Waiting for provider to be ready..."
    
    local max_attempts=30
    local attempt=0
    
    while [ $attempt -lt $max_attempts ]; do
        if kubectl get deployment -n crossplane-system crossplane-provider-proxmox &> /dev/null; then
            if kubectl wait --for=condition=available --timeout=60s \
                deployment/crossplane-provider-proxmox -n crossplane-system &> /dev/null; then
                log_success "Provider is ready"
                return 0
            fi
        fi
        attempt=$((attempt + 1))
        sleep 2
    done
    
    log_warning "Provider may not be ready yet"
    return 1
}

check_provider_status() {
    log "Checking provider status..."
    
    if kubectl get deployment -n crossplane-system crossplane-provider-proxmox &> /dev/null; then
        kubectl get deployment -n crossplane-system crossplane-provider-proxmox
        echo ""
        kubectl get pods -n crossplane-system -l app=crossplane-provider-proxmox
        echo ""
        log "Provider logs:"
        kubectl logs -n crossplane-system -l app=crossplane-provider-proxmox --tail=20 || true
    else
        log_warning "Provider deployment not found"
    fi
}

create_providerconfig() {
    log "Creating ProviderConfig..."
    
    PROVIDER_CONFIG="${PROVIDER_DIR}/examples/provider-config.yaml"
    
    if [ ! -f "${PROVIDER_CONFIG}" ]; then
        log_warning "ProviderConfig example not found: ${PROVIDER_CONFIG}"
        return
    fi
    
    log "Note: ProviderConfig requires credentials secret"
    log "Create secret first with:"
    echo "  kubectl create secret generic proxmox-credentials \\"
    echo "    --from-literal=credentials.json='{\"username\":\"root@pam\",\"token\":\"...\"}' \\"
    echo "    -n crossplane-system"
    echo ""
    log "Then apply ProviderConfig:"
    echo "  kubectl apply -f ${PROVIDER_CONFIG}"
    echo ""
    
    read -p "Apply ProviderConfig now? (y/N) " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        kubectl apply -f "${PROVIDER_CONFIG}" || log_warning "Failed to apply ProviderConfig"
        log_success "ProviderConfig applied"
    else
        log "Skipping ProviderConfig creation"
    fi
}

main() {
    log "Starting Proxmox Provider Deployment..."
    log "========================================"
    
    check_prerequisites
    deploy_crds
    deploy_provider
    wait_for_provider
    check_provider_status
    create_providerconfig
    
    log ""
    log "========================================"
    log_success "Deployment completed!"
    log ""
    log "Next steps:"
    log "1. Create credentials secret (see above)"
    log "2. Apply ProviderConfig"
    log "3. Verify provider connectivity"
    log "4. Test VM creation"
}

main "$@"

