#!/bin/bash
# Monitor VM deletion progress

PROXMOX_PASS="L@kers2010"
SITE1="192.168.11.10"
SITE2="192.168.11.11"

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

echo "=========================================="
echo "VM Deletion Progress Monitor"
echo "=========================================="
echo ""

echo -e "${CYAN}Site 1 (ml110-01) - ${SITE1}${NC}"
echo "VMs remaining:"
VM_COUNT1=$(sshpass -p "${PROXMOX_PASS}" ssh -o StrictHostKeyChecking=no root@${SITE1} "qm list 2>/dev/null | tail -n +2 | wc -l")
if [ "${VM_COUNT1}" -eq 0 ]; then
    echo -e "${GREEN}  ✅ All VMs deleted${NC}"
else
    sshpass -p "${PROXMOX_PASS}" ssh -o StrictHostKeyChecking=no root@${SITE1} "qm list 2>/dev/null | tail -n +2"
    echo -e "${YELLOW}  ⏳ ${VM_COUNT1} VMs remaining${NC}"
fi

PROCESS_COUNT1=$(sshpass -p "${PROXMOX_PASS}" ssh -o StrictHostKeyChecking=no root@${SITE1} "ps aux | grep 'qm destroy' | grep -v grep | wc -l" 2>/dev/null || echo "0")
if [ "${PROCESS_COUNT1}" -gt 0 ]; then
    echo -e "${BLUE}  🔄 ${PROCESS_COUNT1} deletion processes running${NC}"
fi

echo ""
echo -e "${CYAN}Site 2 (r630-01) - ${SITE2}${NC}"
echo "VMs remaining:"
VM_COUNT2=$(sshpass -p "${PROXMOX_PASS}" ssh -o StrictHostKeyChecking=no root@${SITE2} "qm list 2>/dev/null | tail -n +2 | wc -l")
if [ "${VM_COUNT2}" -eq 0 ]; then
    echo -e "${GREEN}  ✅ All VMs deleted${NC}"
else
    sshpass -p "${PROXMOX_PASS}" ssh -o StrictHostKeyChecking=no root@${SITE2} "qm list 2>/dev/null | tail -n +2"
    echo -e "${YELLOW}  ⏳ ${VM_COUNT2} VMs remaining${NC}"
fi

PROCESS_COUNT2=$(sshpass -p "${PROXMOX_PASS}" ssh -o StrictHostKeyChecking=no root@${SITE2} "ps aux | grep 'qm destroy' | grep -v grep | wc -l" 2>/dev/null || echo "0")
if [ "${PROCESS_COUNT2}" -gt 0 ]; then
    echo -e "${BLUE}  🔄 ${PROCESS_COUNT2} deletion processes running${NC}"
fi

echo ""
TOTAL_VMS=$((VM_COUNT1 + VM_COUNT2))
TOTAL_PROCESSES=$((PROCESS_COUNT1 + PROCESS_COUNT2))

echo "=========================================="
echo "Summary:"
echo "  Total VMs remaining: ${TOTAL_VMS}"
echo "  Total deletion processes: ${TOTAL_PROCESSES}"
echo "=========================================="

if [ "${TOTAL_VMS}" -eq 0 ]; then
    echo -e "${GREEN}✅ All VMs deleted successfully!${NC}"
    exit 0
elif [ "${TOTAL_PROCESSES}" -gt 0 ]; then
    echo -e "${BLUE}⏳ Deletion in progress...${NC}"
    exit 1
else
    echo -e "${YELLOW}⚠️  No deletion processes running${NC}"
    exit 2
fi

