#!/usr/bin/env bash
# Check for IP conflicts and configuration issues in Proxmox containers
# Detects duplicate IPs, invalid IPs (.0, .255), and missing configurations

set -euo pipefail

PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"

echo "═══════════════════════════════════════════════════════════"
echo "  VMID IP Configuration Check"
echo "═══════════════════════════════════════════════════════════"
echo ""

# Get all VMIDs
VMIDS=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct list | awk 'NR>1{print \$1}'")

# 1. Check for duplicate IPs
echo "1. Checking for duplicate IP assignments..."
DUPLICATES=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct list | awk 'NR>1{print \$1}' | while read -r vmid; do
        pct config \"\$vmid\" 2>/dev/null | sed -n 's/.*ip=\([^,]*\).*/\$vmid \1/p'
    done | sed 's#/.*##' | awk '\$2 != \"dhcp\" && \$2 != \"N/A\"' | sort -k2,2 | \
    awk '{ ips[\$2]=ips[\$2] ? ips[\$2] \",\" \$1 : \$1; count[\$2]++ } \
    END { for (ip in count) if (count[ip] > 1) print ip \" -> \" ips[ip] }' | sort -V")

if [ -n "$DUPLICATES" ]; then
    echo "⚠️  DUPLICATE IPs FOUND:"
    echo "$DUPLICATES" | while read -r line; do
        echo "   $line"
    done
else
    echo "✅ No duplicate IPs found"
fi
echo ""

# 2. Check for invalid IPs (.0 or .255)
echo "2. Checking for invalid IPs (network/broadcast addresses)..."
BAD_IPS=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct list | awk 'NR>1{print \$1}' | while read -r vmid; do
        ip=\$(pct config \"\$vmid\" 2>/dev/null | sed -n 's/.*ip=\([^,]*\).*/\1/p')
        if [ -n \"\$ip\" ] && [ \"\$ip\" != \"dhcp\" ]; then
            ipbase=\${ip%/*}
            last=\${ipbase##*.}
            if [ \"\$last\" = \"0\" ] || [ \"\$last\" = \"255\" ]; then
                echo \"\$vmid \$ip\"
            fi
        fi
    done")

if [ -n "$BAD_IPS" ]; then
    echo "⚠️  INVALID IPs FOUND:"
    echo "$BAD_IPS" | while read -r line; do
        echo "   $line"
    done
else
    echo "✅ No invalid IPs found"
fi
echo ""

# 3. Show all networks per container
echo "3. Listing all networks per container (showing conflicts only)..."
ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct list | awk 'NR>1{print \$1}' | while read -r vmid; do
        pct config \"\$vmid\" 2>/dev/null | \
        awk -v id=\"\$vmid\" -F\": \" '/^net[0-9]+: / {
            ip=\"N/A\"
            if (match(\$2, /ip=([^,]+)/, a)) ip=a[1]
            if (match(\$2, /bridge=([^,]+)/, b)) bridge=b[1]
            print id, \$1, ip, bridge
        }'
    done" | sort -k3,3 | \
    awk '{
        key = $3 " " $4
        if (key != "N/A N/A" && key != "dhcp N/A") {
            if (seen[key]) {
                print "⚠️  CONFLICT: IP=" $3 " Bridge=" $4 " -> VMIDs: " seen[key] ", " $1
                conflicts=1
            } else {
                seen[key] = $1
            }
        }
    } END { if (!conflicts) print "✅ No network conflicts found (same IP + same bridge)" }'

echo ""
echo "═══════════════════════════════════════════════════════════"
echo "  Check Complete"
echo "═══════════════════════════════════════════════════════════"
