#!/bin/bash
# Comprehensive IP address audit for all VMs/containers across all Proxmox hosts
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/load-physical-inventory.sh" 2>/dev/null || true

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

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[⚠]${NC} $1"; }
log_error() { echo -e "${RED}[✗]${NC} $1"; }
log_section() { echo -e "\n${CYAN}=== $1 ===${NC}\n"; }

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

log_section "IP Address Audit - All Proxmox Hosts"

declare -A IP_TO_VMIDS
declare -A CONFLICTS

for hostname in "${!HOSTS[@]}"; do
    ip="${HOSTS[$hostname]%%:*}"
    password="${HOSTS[$hostname]#*:}"
    
    log_info "Scanning ${hostname} (${ip})..."
    
    sshpass -p "$password" ssh -o StrictHostKeyChecking=no root@"$ip" bash <<'ENDSSH' 2>/dev/null | while IFS=: read -r type vmid ip_addr hostname_vm status; do
        pct list 2>/dev/null | awk 'NR>1 {print $1, $3}' | while read vmid status; do
            if [[ "$status" == "running" ]] || [[ "$status" == "stopped" ]]; then
                ip=$(pct config "$vmid" 2>/dev/null | grep -oP 'ip=\K[^,]+' | head -1 || echo "N/A")
                hostname=$(pct config "$vmid" 2>/dev/null | grep -oP 'hostname=\K[^,]+' | head -1 || echo "N/A")
                if [[ "$ip" != "N/A" ]] && [[ "$ip" != "dhcp" ]] && [[ -n "$ip" ]]; then
                    ip_base="${ip%/*}"
                    echo "CT:$vmid:$ip_base:$hostname:$status"
                fi
            fi
        done
ENDSSH
        if [[ -n "$ip_addr" ]] && [[ "$ip_addr" != "N/A" ]] && [[ "$ip_addr" != "DHCP" ]]; then
            key="${hostname}:${type}:${vmid}"
            if [[ -n "${IP_TO_VMIDS[$ip_addr]:-}" ]]; then
                IP_TO_VMIDS[$ip_addr]="${IP_TO_VMIDS[$ip_addr]},$key"
                CONFLICTS[$ip_addr]="true"
            else
                IP_TO_VMIDS[$ip_addr]="$key"
            fi
        fi
    done
done

log_section "Conflict Detection"
conflict_count=0
for ip in "${!CONFLICTS[@]}"; do
    conflict_count=$((conflict_count + 1))
    log_error "CONFLICT: IP $ip"
    echo "  Used by: ${IP_TO_VMIDS[$ip]}"
done

if [[ $conflict_count -eq 0 ]]; then
    log_success "No conflicts found!"
fi
