#!/usr/bin/env bash
# Find all VMIDs using IPs in the reserved range (192.168.11.10-192.168.11.25)
# These IPs are reserved for physical servers
# Usage: ./scripts/find-reserved-ip-conflicts.sh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

# Reserved IP range for physical servers
RESERVED_START=10
RESERVED_END=25

# Proxmox hosts
declare -a PROXMOX_HOSTS=(
    "192.168.11.10:ml110:L@kers2010"
    "192.168.11.11:r630-01:password"
    "192.168.11.12:r630-02:password"
)

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

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

echo ""
log_info "═══════════════════════════════════════════════════════════"
log_info "  FINDING VMIDs USING RESERVED IP RANGE"
log_info "  Reserved Range: 192.168.11.10 - 192.168.11.25"
log_info "═══════════════════════════════════════════════════════════"
echo ""

declare -a CONFLICTS=()

# Check each Proxmox host
for host_info in "${PROXMOX_HOSTS[@]}"; do
    IFS=':' read -r ip hostname password <<< "$host_info"
    
    log_info "Checking $hostname ($ip)..."
    
    # Get all containers
    CONTAINERS=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${ip} \
        "pct list 2>/dev/null | tail -n +2 | awk '{print \$1}'" 2>/dev/null || echo "")
    
    if [[ -z "$CONTAINERS" ]]; then
        log_warn "  No containers found or cannot access"
        continue
    fi
    
    # Check each container
    while IFS= read -r vmid; do
        if [[ -z "$vmid" ]]; then
            continue
        fi
        
        # Get IP address
        ip_config=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${ip} \
            "pct config $vmid 2>/dev/null | grep -oP 'ip=\\K[^,]+' | head -1" 2>/dev/null || echo "")
        
        if [[ -z "$ip_config" ]] || [[ "$ip_config" == "dhcp" ]]; then
            continue
        fi
        
        # Extract IP base (remove /24)
        ip_base="${ip_config%/*}"
        
        # Check if IP is in reserved range
        if [[ "$ip_base" =~ ^192\.168\.11\.([0-9]+)$ ]]; then
            ip_octet="${BASH_REMATCH[1]}"
            
            if [[ $ip_octet -ge $RESERVED_START ]] && [[ $ip_octet -le $RESERVED_END ]]; then
                # Get hostname
                container_hostname=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${ip} \
                    "pct config $vmid 2>/dev/null | grep -oP 'hostname=\\K[^,]+' | head -1" 2>/dev/null || echo "unknown")
                
                # Get status
                status=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${ip} \
                    "pct status $vmid 2>/dev/null | awk '{print \$2}'" 2>/dev/null || echo "unknown")
                
                log_warn "  ⚠️  VMID $vmid ($container_hostname) on $hostname: $ip_base [$status]"
                
                CONFLICTS+=("$hostname:$vmid:$container_hostname:$ip_base:$status")
            fi
        fi
    done <<< "$CONTAINERS"
done

echo ""
log_info "═══════════════════════════════════════════════════════════"
log_info "  SUMMARY"
log_info "═══════════════════════════════════════════════════════════"
echo ""

if [[ ${#CONFLICTS[@]} -eq 0 ]]; then
    log_success "✅ No VMIDs found using reserved IP range"
else
    log_warn "⚠️  Found ${#CONFLICTS[@]} VMID(s) using reserved IPs:"
    echo ""
    printf "%-12s | %-6s | %-25s | %-15s | %-8s\n" "Node" "VMID" "Hostname" "IP Address" "Status"
    echo "------------|--------|---------------------------|----------------|----------"
    
    for conflict in "${CONFLICTS[@]}"; do
        IFS=':' read -r node vmid hostname ip status <<< "$conflict"
        printf "%-12s | %-6s | %-25s | %-15s | %-8s\n" "$node" "$vmid" "$hostname" "$ip" "$status"
    done
    
    echo ""
    log_info "These VMIDs need to be changed to IPs outside the reserved range (192.168.11.26-99 or 192.168.11.113-139, etc.)"
fi

echo ""
