#!/bin/bash
# check-all-vm-ips.sh
# Check IP addresses for all VMs via guest agent and ARP table

set -euo pipefail

PROXMOX_1_HOST="192.168.11.10"
PROXMOX_2_HOST="192.168.11.11"
PROXMOX_PASS="L@kers2010"

SITE1_VMS="136 139 141 142 145 146 150 151"
SITE2_VMS="101 104 137 138 144 148"

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

check_vm_ip() {
    local host=$1
    local vmid=$2
    local vmname=$3
    
    printf "%-8s %-30s " "$vmid" "$vmname"
    
    # Method 1: Try guest agent
    guest_ip=$(sshpass -p "$PROXMOX_PASS" ssh -o StrictHostKeyChecking=no root@$host \
        "qm guest exec $vmid -- 'hostname -I' 2>&1" 2>/dev/null || true)
    
    if echo "$guest_ip" | grep -qE '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+'; then
        ips=$(echo "$guest_ip" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' | tr '\n' ',' | sed 's/,$//')
        echo -e "${GREEN}✅ $ips${NC} (via guest agent)"
        return 0
    fi
    
    # Method 2: Try ARP table lookup
    mac=$(sshpass -p "$PROXMOX_PASS" ssh -o StrictHostKeyChecking=no root@$host \
        "qm config $vmid | grep -oP 'virtio=\K[^,]+' | head -1 | tr '[:upper:]' '[:lower:]'" 2>/dev/null || echo "")
    
    if [ -n "$mac" ]; then
        arp_ip=$(sshpass -p "$PROXMOX_PASS" ssh -o StrictHostKeyChecking=no root@$host \
            "ip neigh show | grep -i \"$mac\" | awk '{print \$1}' | head -1" 2>/dev/null || echo "")
        
        if [ -n "$arp_ip" ] && [ "$arp_ip" != "NOT_FOUND" ]; then
            echo -e "${YELLOW}⚠️  $arp_ip${NC} (via ARP table - guest agent not running)"
            return 1
        fi
    fi
    
    # Check guest agent status
    if echo "$guest_ip" | grep -q "QEMU guest agent is not running"; then
        echo -e "${YELLOW}⚠️  Guest agent not running${NC}"
    elif echo "$guest_ip" | grep -q "No QEMU guest agent configured"; then
        echo -e "${RED}❌ Guest agent not configured${NC}"
    else
        echo -e "${YELLOW}⚠️  No IP found${NC}"
    fi
    return 1
}

echo "=========================================="
echo "VM IP Address Check - All Methods"
echo "=========================================="
echo ""
printf "%-8s %-30s %s\n" "VMID" "Name" "IP Address(es) & Method"
printf "%-8s %-30s %s\n" "----" "----" "----------------------"
echo ""

echo "Site 1 (ml110-01):"
site1_guest=0
site1_arp=0
site1_none=0

for vmid in $SITE1_VMS; do
    name=$(sshpass -p "$PROXMOX_PASS" ssh -o StrictHostKeyChecking=no root@$PROXMOX_1_HOST \
        "qm config $vmid | grep '^name:' | cut -d' ' -f2" || echo "unknown")
    
    result=$(check_vm_ip "$PROXMOX_1_HOST" "$vmid" "$name" 2>&1)
    echo "$result"
    
    if echo "$result" | grep -q "via guest agent"; then
        site1_guest=$((site1_guest + 1))
    elif echo "$result" | grep -q "via ARP table"; then
        site1_arp=$((site1_arp + 1))
    else
        site1_none=$((site1_none + 1))
    fi
done

echo ""
echo "Site 2 (r630-01):"
site2_guest=0
site2_arp=0
site2_none=0

for vmid in $SITE2_VMS; do
    name=$(sshpass -p "$PROXMOX_PASS" ssh -o StrictHostKeyChecking=no root@$PROXMOX_2_HOST \
        "qm config $vmid | grep '^name:' | cut -d' ' -f2" || echo "unknown")
    
    result=$(check_vm_ip "$PROXMOX_2_HOST" "$vmid" "$name" 2>&1)
    echo "$result"
    
    if echo "$result" | grep -q "via guest agent"; then
        site2_guest=$((site2_guest + 1))
    elif echo "$result" | grep -q "via ARP table"; then
        site2_arp=$((site2_arp + 1))
    else
        site2_none=$((site2_none + 1))
    fi
done

echo ""
echo "=========================================="
echo "Summary"
echo "=========================================="

total_guest=$((site1_guest + site2_guest))
total_arp=$((site1_arp + site2_arp))
total_none=$((site1_none + site2_none))
total=$((total_guest + total_arp + total_none))

echo "Total VMs: $total"
echo -e "${GREEN}VMs with IP via guest agent: $total_guest${NC}"
echo -e "${YELLOW}VMs with IP via ARP table: $total_arp${NC}"
echo -e "${RED}VMs without IP: $total_none${NC}"
echo ""

# Check Proxmox IP assignment capability
echo "=========================================="
echo "Proxmox IP Assignment Capability"
echo "=========================================="

if [ $total_guest -gt 0 ]; then
    echo -e "${GREEN}✅ Proxmox CAN assign IP addresses via guest agent${NC}"
    echo "   Guest agent is working for $total_guest VM(s)"
else
    echo -e "${YELLOW}⚠️  Proxmox CANNOT assign IP addresses via guest agent yet${NC}"
    echo "   Guest agent service is not running in VMs"
fi

if [ $total_arp -gt 0 ]; then
    echo -e "${YELLOW}⚠️  $total_arp VM(s) have IPs visible in ARP table${NC}"
    echo "   These VMs have network connectivity but guest agent not running"
fi

if [ $total_none -gt 0 ]; then
    echo -e "${RED}❌ $total_none VM(s) have no IP addresses${NC}"
    echo "   These VMs may not be fully booted or have network issues"
fi

echo ""
echo "=========================================="
echo "Recommendations"
echo "=========================================="

if [ $total_guest -eq 0 ]; then
    echo "1. Guest agent package needs to be installed/started in VMs"
    echo "2. Wait for cloud-init to complete, or manually install:"
    echo "   sudo apt-get install -y qemu-guest-agent"
    echo "   sudo systemctl enable qemu-guest-agent"
    echo "   sudo systemctl start qemu-guest-agent"
    echo "3. Once guest agent is running, Proxmox will automatically"
    echo "   detect and assign IP addresses"
fi

if [ $total_arp -gt 0 ]; then
    echo "4. VMs with ARP table IPs have network connectivity"
    echo "   but need guest agent for Proxmox to manage them properly"
fi

echo ""

