#!/bin/bash
# Simple IP audit - checks all VMs/containers for IP conflicts
set -e

source "$(dirname "$0")/load-physical-inventory.sh" 2>/dev/null || true

HOSTS="ml110:${PROXMOX_HOST_ML110:-192.168.11.10}:${PROXMOX_PASS_ML110:-L@kers2010} pve:${PROXMOX_HOST_R630_01:-192.168.11.11}:${PROXMOX_PASS_R630_01:-password} pve2:${PROXMOX_HOST_R630_02:-192.168.11.12}:${PROXMOX_PASS_R630_02:-password}"

echo "=== IP Address Audit ==="
echo ""

TMP=$(mktemp)
for host_info in $HOSTS; do
    IFS=: read -r hostname ip password <<< "$host_info"
    echo "Scanning $hostname ($ip)..."
    sshpass -p "$password" ssh -o StrictHostKeyChecking=no root@"$ip" "pct list 2>/dev/null | awk 'NR>1 {print \$1}' | while read vmid; do ip=\$(pct config \$vmid 2>/dev/null | grep -oP 'ip=\K[^,]+' | head -1); if [[ -n \"\$ip\" ]] && [[ \"\$ip\" != \"dhcp\" ]]; then echo \"$hostname:CT:\$vmid:\${ip%/*}\"; fi; done" 2>/dev/null >> "$TMP" || true
done

echo ""
echo "=== All VM/Container IPs ==="
printf "%-15s %-8s %-6s %-15s\n" "IP Address" "Type" "VMID" "Proxmox Host"
echo "------------------------------------------------"
sort -t: -k4 -V "$TMP" | while IFS=: read -r host type vmid ip; do
    printf "%-15s %-8s %-6s %-15s\n" "$ip" "$type" "$vmid" "$host"
done

echo ""
echo "=== Conflict Check ==="
conflicts=$(sort -t: -k4 "$TMP" | cut -d: -f4 | uniq -d)
if [[ -z "$conflicts" ]]; then
    echo "✓ No IP conflicts found"
else
    echo "✗ Conflicts found:"
    echo "$conflicts" | while read ip; do
        echo "  $ip used by:"
        grep ":$ip$" "$TMP" | sed 's/^/    /'
    done
fi

rm -f "$TMP"
