#!/bin/bash
# Continuous VM Deployment Monitor
# Monitors VM deployment progress and provides real-time updates

set -e

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

INTERVAL=${1:-30}  # Default 30 seconds

echo "=========================================="
echo "VM Deployment Continuous Monitor"
echo "=========================================="
echo "Update interval: ${INTERVAL} seconds"
echo "Press Ctrl+C to stop"
echo ""

PREV_COUNT=0
ITERATION=0

while true; do
    ITERATION=$((ITERATION + 1))
    TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
    
    # Get counts
    TOTAL=$(kubectl get proxmoxvm -A --no-headers 2>&1 | wc -l)
    WITH_VMID=$(kubectl get proxmoxvm -A -o jsonpath='{range .items[*]}{.status.vmId}{"\n"}{end}' 2>&1 | grep -v "^$" | wc -l)
    PENDING=$((TOTAL - WITH_VMID))
    NEW_VMS=$((WITH_VMID - PREV_COUNT))
    
    # Provider status
    PROVIDER_STATUS=$(kubectl get pods -n crossplane-system -l app=crossplane-provider-proxmox -o jsonpath='{.items[0].status.phase}' 2>&1 || echo "Unknown")
    
    # Check for errors
    AUTH_ERRORS=$(kubectl logs -n crossplane-system -l app=crossplane-provider-proxmox --since=1m 2>&1 | grep -i "invalid PVE ticket\|401.*authentication" | wc -l)
    
    echo -e "${BLUE}[$TIMESTAMP] Iteration $ITERATION${NC}"
    echo "  Provider: $PROVIDER_STATUS"
    echo "  Total VMs: $TOTAL"
    echo -e "  ${GREEN}Created (with VMID): $WITH_VMID${NC}"
    echo -e "  ${YELLOW}Pending: $PENDING${NC}"
    
    if [ $NEW_VMS -gt 0 ]; then
        echo -e "  ${GREEN}✨ New VMs created: +$NEW_VMS${NC}"
    fi
    
    if [ $AUTH_ERRORS -gt 0 ]; then
        echo -e "  ${RED}⚠️  Authentication errors: $AUTH_ERRORS${NC}"
    else
        echo -e "  ${GREEN}✅ No authentication errors${NC}"
    fi
    
    # Progress percentage
    if [ $TOTAL -gt 0 ]; then
        PERCENT=$((WITH_VMID * 100 / TOTAL))
        echo "  Progress: $PERCENT% ($WITH_VMID/$TOTAL)"
    fi
    
    # Show some VMs with VMID
    if [ $WITH_VMID -gt 0 ]; then
        echo ""
        echo "  Recent VMs with VMID:"
        kubectl get proxmoxvm -A -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.vmId}{"\n"}{end}' 2>&1 | grep -v "\t$" | tail -5 | sed 's/^/    /'
    fi
    
    PREV_COUNT=$WITH_VMID
    
    echo ""
    echo "----------------------------------------"
    sleep $INTERVAL
done

