#!/usr/bin/env bash
# Fix container IP addresses - configure static IPs in 192.168.11.X/24 range
# This script updates existing containers to use static IP addresses from inventory.example

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# PROJECT_ROOT should be one level up from scripts directory
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

# Source common functions
if [[ -f "$PROJECT_ROOT/lib/common.sh" ]]; then
    source "$PROJECT_ROOT/lib/common.sh"
else
    log_info() { echo "[INFO] $1"; }
    log_success() { echo "[✓] $1"; }
    log_warn() { echo "[WARNING] $1"; }
    log_error() { echo "[ERROR] $1"; exit 1; }
    error_exit() { echo "[ERROR] $1"; exit 1; }
fi

# Load configuration files
load_config 2>/dev/null || true
if [[ -f "$PROJECT_ROOT/config/network.conf" ]]; then
    source "$PROJECT_ROOT/config/network.conf"
fi

# IP address mapping from inventory.example
declare -A VMID_IPS
VMID_IPS[1000]="192.168.11.100"  # validator-1
VMID_IPS[1001]="192.168.11.101"  # validator-2
VMID_IPS[1002]="192.168.11.102"  # validator-3
VMID_IPS[1003]="192.168.11.103"  # validator-4
VMID_IPS[1004]="192.168.11.104"  # validator-5
VMID_IPS[1500]="192.168.11.150"  # sentry-1
VMID_IPS[1501]="192.168.11.151"  # sentry-2
VMID_IPS[1502]="192.168.11.152"  # sentry-3
VMID_IPS[1503]="192.168.11.153"  # sentry-4
VMID_IPS[2500]="192.168.11.250"  # rpc-1
VMID_IPS[2501]="192.168.11.251"  # rpc-2
VMID_IPS[2502]="192.168.11.252"  # rpc-3

GATEWAY="${GATEWAY:-192.168.11.1}"
NETMASK="${NETMASK:-24}"
BRIDGE="${PROXMOX_BRIDGE:-vmbr0}"

# Force correct gateway if network.conf has wrong value
if [[ "$GATEWAY" == "10.3.1.1" ]]; then
    GATEWAY="192.168.11.1"
fi

log_info "Fixing container IP addresses to use static 192.168.11.X/24 range"
log_info "Gateway: $GATEWAY, Bridge: $BRIDGE"

# Check if running on Proxmox host
if ! command_exists pct; then
    error_exit "This script must be run on Proxmox host (pct command not found)"
fi

check_root

# Function to configure static IP for a container
configure_static_ip() {
    local vmid="$1"
    local ip_address="$2"
    
    if ! pct list | grep -q "^\s*$vmid\s"; then
        log_warn "Container $vmid does not exist, skipping"
        return 1
    fi
    
    log_info "Configuring static IP $ip_address/$NETMASK for container $vmid"
    
    # Stop container if running (required for network config changes)
    local was_running=false
    if pct status "$vmid" 2>/dev/null | grep -q "status: running"; then
        was_running=true
        log_info "Stopping container $vmid to apply network changes..."
        pct stop "$vmid" || log_warn "Failed to stop container $vmid"
        sleep 2
    fi
    
    # Configure static IP using pct set
    # Format: bridge=vmbr0,name=eth0,ip=192.168.11.100/24,gw=192.168.11.1,type=veth
    # Note: NETMASK should be in CIDR format (24, not 255.255.255.0)
    local cidr_mask="$NETMASK"
    if [[ "$NETMASK" == "255.255.255.0" ]]; then
        cidr_mask="24"
    fi
    local net_config="bridge=$BRIDGE,name=eth0,ip=$ip_address/$cidr_mask,gw=$GATEWAY,type=veth"
    
    log_info "Setting network configuration: $net_config"
    if pct set "$vmid" --net0 "$net_config"; then
        log_success "Network configuration updated for container $vmid"
    else
        log_error "Failed to update network configuration for container $vmid"
        return 1
    fi
    
    # Also configure DNS servers
    pct set "$vmid" --nameserver "8.8.8.8 8.8.4.4" 2>/dev/null || log_warn "Failed to set DNS servers for $vmid"
    
    # Start container if it was running before
    if [[ "$was_running" == "true" ]]; then
        log_info "Starting container $vmid..."
        pct start "$vmid" || log_warn "Failed to start container $vmid"
        
        # Wait for container to be running
        local max_wait=30
        local waited=0
        while ! pct status "$vmid" 2>/dev/null | grep -q "status: running" && [[ $waited -lt $max_wait ]]; do
            sleep 1
            waited=$((waited + 1))
        done
        
        if pct status "$vmid" 2>/dev/null | grep -q "status: running"; then
            log_success "Container $vmid is running"
            
            # Wait a bit more for network to come up
            sleep 3
            
            # Verify IP address
            local actual_ip=$(pct exec "$vmid" -- ip -4 addr show dev eth0 2>/dev/null | awk '/inet / {print $2}' | cut -d'/' -f1)
            if [[ "$actual_ip" == "$ip_address" ]]; then
                log_success "Verified IP address $ip_address on container $vmid"
            else
                log_warn "IP address mismatch: expected $ip_address, got $actual_ip (may need container restart)"
            fi
        else
            log_warn "Container $vmid did not start successfully"
        fi
    fi
    
    return 0
}

# Process all containers
processed=0
failed=0

for vmid in "${!VMID_IPS[@]}"; do
    ip_address="${VMID_IPS[$vmid]}"
    
    if configure_static_ip "$vmid" "$ip_address"; then
        processed=$((processed + 1))
    else
        failed=$((failed + 1))
    fi
    
    echo ""  # Blank line between containers
done

log_success "IP address configuration completed!"
log_info "Summary:"
log_info "  Processed: $processed containers"
if [[ $failed -gt 0 ]]; then
    log_warn "  Failed: $failed containers"
fi
log_info ""
log_info "Next steps:"
log_info "1. Verify IP addresses: pct exec <vmid> -- ip addr show eth0"
log_info "2. Test connectivity: pct exec <vmid> -- ping -c 3 $GATEWAY"
log_info "3. Update static-nodes.json with new IP addresses if changed"

