#!/usr/bin/env bash
# Fix VMIDs using reserved IP range (192.168.11.10-192.168.11.25)
# Changes IPs to available addresses outside the reserved range
# Usage: ./scripts/fix-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

# 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 "  FIXING RESERVED IP CONFLICTS"
log_info "  Reserved Range: 192.168.11.10 - 192.168.11.25"
log_info "═══════════════════════════════════════════════════════════"
echo ""

# VMIDs that need IP changes
# Format: node:vmid:hostname:current_ip:new_ip
declare -a FIXES=(
    "r630-02:105:nginxproxymanager:192.168.11.21:192.168.11.26"
    "r630-02:130:monitoring-1:192.168.11.22:192.168.11.27"
)

# Node IPs
declare -A NODE_IPS=(
    ["ml110"]="192.168.11.10"
    ["r630-01"]="192.168.11.11"
    ["r630-02"]="192.168.11.12"
)

# Node passwords
declare -A NODE_PASSWORDS=(
    ["ml110"]="L@kers2010"
    ["r630-01"]="password"
    ["r630-02"]="password"
)

log_info "Found ${#FIXES[@]} VMID(s) to fix:"
echo ""

for fix in "${FIXES[@]}"; do
    IFS=':' read -r node vmid hostname current_ip new_ip <<< "$fix"
    log_info "  VMID $vmid ($hostname) on $node: $current_ip → $new_ip"
done

echo ""
read -p "Continue with IP changes? (y/N): " -n 1 -r
echo ""

if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    log_info "Cancelled"
    exit 0
fi

echo ""

# Apply fixes
for fix in "${FIXES[@]}"; do
    IFS=':' read -r node vmid hostname current_ip new_ip <<< "$fix"
    node_ip="${NODE_IPS[$node]}"
    
    log_info "Fixing VMID $vmid ($hostname) on $node..."
    
    # Get current network configuration
    current_config=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${node_ip} \
        "pct config $vmid 2>/dev/null | grep '^net0:'" || echo "")
    
    if [[ -z "$current_config" ]]; then
        log_error "  Cannot read configuration for VMID $vmid"
        continue
    fi
    
    # Extract MAC address and other settings
    mac=$(echo "$current_config" | grep -oP 'hwaddr=\K[^,]+' || echo "")
    bridge=$(echo "$current_config" | grep -oP 'bridge=\K[^,]+' || echo "vmbr0")
    gw=$(echo "$current_config" | grep -oP 'gw=\K[^,]+' || echo "192.168.11.1")
    type=$(echo "$current_config" | grep -oP 'type=\K[^,]+' || echo "veth")
    
    if [[ -z "$mac" ]]; then
        log_error "  Cannot extract MAC address"
        continue
    fi
    
    # Stop container
    log_info "  Stopping container..."
    ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${node_ip} \
        "pct stop $vmid 2>/dev/null || true"
    sleep 2
    
    # Change IP address
    log_info "  Changing IP from $current_ip to $new_ip..."
    new_net_config="name=eth0,bridge=${bridge},gw=${gw},ip=${new_ip}/24,hwaddr=${mac},type=${type}"
    
    if ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${node_ip} \
        "pct set $vmid -net0 \"$new_net_config\"" 2>&1; then
        log_success "  IP address changed successfully"
    else
        log_error "  Failed to change IP address"
        continue
    fi
    
    # Start container
    log_info "  Starting container..."
    ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${node_ip} \
        "pct start $vmid" || {
        log_warn "  Container may need manual start"
    }
    
    sleep 3
    
    # Verify new IP
    log_info "  Verifying new IP..."
    new_ip_check=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${node_ip} \
        "pct config $vmid 2>/dev/null | grep -oP 'ip=\\K[^,]+' | head -1" || echo "")
    
    if [[ "$new_ip_check" == "${new_ip}/24" ]]; then
        log_success "  ✅ Verified: IP is now $new_ip"
    else
        log_warn "  ⚠️  IP verification: Expected ${new_ip}/24, got $new_ip_check"
    fi
    
    echo ""
done

log_success "═══════════════════════════════════════════════════════════"
log_success "  IP CONFLICTS FIXED"
log_success "═══════════════════════════════════════════════════════════"
echo ""
log_info "Summary of changes:"
for fix in "${FIXES[@]}"; do
    IFS=':' read -r node vmid hostname current_ip new_ip <<< "$fix"
    log_info "  ✅ VMID $vmid ($hostname): $current_ip → $new_ip"
done
echo ""
log_info "Next steps:"
log_info "  1. Update any configuration files that reference the old IPs"
log_info "  2. Update DNS records if needed"
log_info "  3. Update firewall rules if needed"
log_info "  4. Test services to ensure they work with new IPs"
echo ""
