#!/bin/bash
# Test deployment with basic-vm.yaml

set -e

echo "=== Test Deployment: basic-vm.yaml ==="
echo ""

# Check if kubectl is available
if ! command -v kubectl &> /dev/null; then
    echo "ERROR: kubectl not found. Please install kubectl and configure kubeconfig."
    exit 1
fi

VM_FILE="examples/production/basic-vm.yaml"
VM_NAME="basic-vm-001"

echo "1. Validating YAML:"
echo "----------------------------------------"
if kubectl apply --dry-run=client -f "$VM_FILE" 2>&1; then
    echo "  ✅ YAML is valid"
else
    echo "  ❌ YAML validation failed"
    exit 1
fi

echo ""
echo "2. Checking if VM already exists:"
echo "----------------------------------------"
if kubectl get proxmoxvm "$VM_NAME" 2>/dev/null; then
    echo "  ⚠️  VM $VM_NAME already exists"
    read -p "  Delete existing VM? (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        echo "  Deleting existing VM..."
        kubectl delete proxmoxvm "$VM_NAME"
        echo "  Waiting for deletion to complete..."
        sleep 5
    else
        echo "  Aborting. Please delete the existing VM manually or choose a different name."
        exit 1
    fi
else
    echo "  ✅ VM $VM_NAME does not exist, proceeding with deployment"
fi

echo ""
echo "3. Deploying VM:"
echo "----------------------------------------"
echo "  Applying $VM_FILE..."
if kubectl apply -f "$VM_FILE"; then
    echo "  ✅ VM deployment initiated"
else
    echo "  ❌ Failed to deploy VM"
    exit 1
fi

echo ""
echo "4. Monitoring deployment:"
echo "----------------------------------------"
echo "  Watching VM status (Ctrl+C to stop)..."
echo ""

# Monitor for up to 5 minutes
TIMEOUT=300
ELAPSED=0
INTERVAL=5

while [ $ELAPSED -lt $TIMEOUT ]; do
    STATUS=$(kubectl get proxmoxvm "$VM_NAME" -o jsonpath='{.status.conditions[?(@.type=="Ready")].status}' 2>/dev/null || echo "Unknown")
    MESSAGE=$(kubectl get proxmoxvm "$VM_NAME" -o jsonpath='{.status.conditions[?(@.type=="Ready")].message}' 2>/dev/null || echo "")
    VMID=$(kubectl get proxmoxvm "$VM_NAME" -o jsonpath='{.status.vmId}' 2>/dev/null || echo "")
    
    echo "  [${ELAPSED}s] Status: $STATUS | VMID: ${VMID:-N/A}"
    if [ -n "$MESSAGE" ]; then
        echo "    Message: $MESSAGE"
    fi
    
    if [ "$STATUS" = "True" ]; then
        echo ""
        echo "  ✅ VM is Ready!"
        break
    fi
    
    sleep $INTERVAL
    ELAPSED=$((ELAPSED + INTERVAL))
done

echo ""
echo "5. Final Status:"
echo "----------------------------------------"
kubectl get proxmoxvm "$VM_NAME" -o wide

echo ""
echo "6. Provider Logs (last 20 lines):"
echo "----------------------------------------"
POD_NAME=$(kubectl get pods -n crossplane-system | grep crossplane-provider-proxmox | head -1 | awk '{print $1}' || echo "")
if [ -n "$POD_NAME" ]; then
    kubectl logs -n crossplane-system "$POD_NAME" --tail=20 2>&1 | sed 's/^/  /'
else
    echo "  ⚠️  Provider pod not found"
fi

echo ""
echo "=== Next Steps ==="
echo ""
echo "1. Check VM in Proxmox:"
echo "   ssh root@<proxmox-node> 'qm status <vmid>'"
echo ""
echo "2. Check cloud-init logs (once VM is accessible):"
echo "   ssh admin@<vm-ip> 'cat /var/log/cloud-init-output.log | tail -50'"
echo ""
echo "3. Verify services:"
echo "   ssh admin@<vm-ip> 'systemctl status qemu-guest-agent chrony unattended-upgrades'"
echo ""

