#!/bin/bash
# deploy-test-vms.sh
# Deploys test VMs to both Proxmox instances via Crossplane

set -euo pipefail

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

# Configuration
PROVIDER_DIR="${PROVIDER_DIR:-./crossplane-provider-proxmox}"
INSTANCE1_MANIFEST="${PROVIDER_DIR}/examples/test-vm-instance-1.yaml"
INSTANCE2_MANIFEST="${PROVIDER_DIR}/examples/test-vm-instance-2.yaml"
WAIT_TIMEOUT="${WAIT_TIMEOUT:-300}"

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"
}

info() {
    echo -e "${BLUE}[INFO]${NC} $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
    
    # Check if provider is deployed
    if ! kubectl get deployment crossplane-provider-proxmox -n crossplane-system &> /dev/null; then
        error "Crossplane provider is not deployed. Run ./scripts/deploy-crossplane-provider.sh first"
    fi
    
    # Check if ProviderConfig exists
    if ! kubectl get providerconfig proxmox-provider-config &> /dev/null; then
        error "ProviderConfig not found. Create it first: kubectl apply -f ${PROVIDER_DIR}/examples/provider-config.yaml"
    fi
    
    log "✓ Prerequisites check passed"
}

deploy_vm() {
    local manifest=$1
    local vm_name=$2
    
    if [ ! -f "$manifest" ]; then
        error "VM manifest not found: ${manifest}"
    fi
    
    log "Deploying VM: ${vm_name}..."
    
    # Apply manifest
    if kubectl apply -f "$manifest"; then
        log "✓ VM manifest applied: ${vm_name}"
    else
        error "Failed to apply VM manifest: ${vm_name}"
    fi
    
    # Wait for VM to be created
    log "Waiting for VM to be ready (timeout: ${WAIT_TIMEOUT}s)..."
    
    local start_time=$(date +%s)
    while true; do
        local current_time=$(date +%s)
        local elapsed=$((current_time - start_time))
        
        if [ $elapsed -gt $WAIT_TIMEOUT ]; then
            warn "Timeout waiting for VM: ${vm_name}"
            return 1
        fi
        
        local state=$(kubectl get proxmoxvm "$vm_name" -o jsonpath='{.status.state}' 2>/dev/null || echo "Unknown")
        local vm_id=$(kubectl get proxmoxvm "$vm_name" -o jsonpath='{.status.vmId}' 2>/dev/null || echo "")
        
        if [ "$state" = "running" ] && [ -n "$vm_id" ]; then
            log "✓ VM is running: ${vm_name} (ID: ${vm_id})"
            return 0
        elif [ "$state" = "failed" ] || [ "$state" = "error" ]; then
            error "VM deployment failed: ${vm_name} (state: ${state})"
        fi
        
        sleep 5
    done
}

get_vm_status() {
    local vm_name=$1
    
    info "VM Status: ${vm_name}"
    info "=================================="
    
    kubectl get proxmoxvm "$vm_name" -o jsonpath='{
        "Name": "{.metadata.name}",
        "State": "{.status.state}",
        "VM ID": "{.status.vmId}",
        "IP Address": "{.status.ipAddress}",
        "Site": "{.spec.forProvider.site}",
        "Node": "{.spec.forProvider.node}"
    }' 2>/dev/null | jq '.' || warn "Could not get VM status"
    
    echo ""
}

test_vm_lifecycle() {
    local vm_name=$1
    
    log "Testing VM lifecycle operations for: ${vm_name}"
    
    # Test stop (if supported)
    info "Note: VM lifecycle operations (start/stop) would be tested here"
    info "This requires VM controller implementation"
}

main() {
    echo ""
    echo "╔══════════════════════════════════════════════════════════════╗"
    echo "║          Test VM Deployment via Crossplane                   ║"
    echo "╚══════════════════════════════════════════════════════════════╝"
    echo ""
    
    check_prerequisites
    echo ""
    
    # Deploy Instance 1 VM
    if [ -f "$INSTANCE1_MANIFEST" ]; then
        local vm1_name=$(grep -A1 "^metadata:" "$INSTANCE1_MANIFEST" | grep "name:" | awk '{print $2}')
        deploy_vm "$INSTANCE1_MANIFEST" "$vm1_name"
        get_vm_status "$vm1_name"
    else
        warn "Instance 1 manifest not found: ${INSTANCE1_MANIFEST}"
    fi
    
    echo ""
    
    # Deploy Instance 2 VM
    if [ -f "$INSTANCE2_MANIFEST" ]; then
        local vm2_name=$(grep -A1 "^metadata:" "$INSTANCE2_MANIFEST" | grep "name:" | awk '{print $2}')
        deploy_vm "$INSTANCE2_MANIFEST" "$vm2_name"
        get_vm_status "$vm2_name"
    else
        warn "Instance 2 manifest not found: ${INSTANCE2_MANIFEST}"
    fi
    
    echo ""
    log "Test VM deployment complete!"
    echo ""
    info "View all VMs: kubectl get proxmoxvm"
    info "View VM details: kubectl describe proxmoxvm <vm-name>"
    info "Delete VM: kubectl delete proxmoxvm <vm-name>"
}

main "$@"

