#!/bin/bash
# Convert DHCP containers to static IPs
# Converts one container at a time with verification

set -euo pipefail

# Color codes
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
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}[⚠]${NC} $1"; }
log_error() { echo -e "${RED}[✗]${NC} $1"; }

# Network settings
GATEWAY="192.168.11.1"
NETMASK="24"
BRIDGE="vmbr0"

# Conversion list (host_ip:vmid:old_ip:new_ip:name:hostname)
declare -a CONVERSIONS=(
    "192.168.11.10:3501:192.168.11.14:192.168.11.28:ccip-monitor-1:ml110"
    "192.168.11.10:3500:192.168.11.15:192.168.11.29:oracle-publisher-1:ml110"
    "192.168.11.12:103:192.168.11.20:192.168.11.30:omada:r630-02"
    "192.168.11.12:104:192.168.11.18:192.168.11.31:gitea:r630-02"
    "192.168.11.12:100:192.168.11.4:192.168.11.32:proxmox-mail-gateway:r630-02"
    "192.168.11.12:101:192.168.11.6:192.168.11.33:proxmox-datacenter-manager:r630-02"
    "192.168.11.12:102:192.168.11.9:192.168.11.34:cloudflared:r630-02"
    "192.168.11.12:6200:192.168.11.7:192.168.11.35:firefly-1:r630-02"
    "192.168.11.12:7811:N/A:192.168.11.36:mim-api-1:r630-02"
)

LOG_FILE="/home/intlc/projects/proxmox/ip_conversion_log_$(date +%Y%m%d_%H%M%S).log"

echo "=== Converting DHCP Containers to Static IPs ===" | tee "$LOG_FILE"
echo "Log file: $LOG_FILE"
echo ""

success_count=0
fail_count=0

for conversion in "${CONVERSIONS[@]}"; do
    IFS=':' read -r host_ip vmid old_ip new_ip name hostname <<< "$conversion"
    
    log_info "Converting VMID $vmid ($name) on $hostname..."
    log_info "  Current IP: $old_ip → New IP: $new_ip"
    
    # Skip if old_ip is N/A (stopped container)
    if [ "$old_ip" = "N/A" ]; then
        log_warn "  Container is stopped, skipping..."
        continue
    fi
    
    # Check if container exists
    if ! ssh -o ConnectTimeout=5 root@"$host_ip" "pct list | grep -q '^$vmid'" 2>/dev/null; then
        log_error "  Container $vmid not found on $hostname"
        fail_count=$((fail_count + 1))
        continue
    fi
    
    # Get current status
    was_running=false
    if ssh -o ConnectTimeout=5 root@"$host_ip" "pct status $vmid 2>/dev/null | grep -q 'status: running'"; then
        was_running=true
        log_info "  Stopping container..."
        ssh -o ConnectTimeout=10 root@"$host_ip" "pct stop $vmid" 2>/dev/null || log_warn "  Warning: Failed to stop container"
        sleep 3
    fi
    
    # Configure static IP
    net_config="bridge=$BRIDGE,name=eth0,ip=$new_ip/$NETMASK,gw=$GATEWAY,type=veth"
    log_info "  Setting network: $net_config"
    
    if ssh -o ConnectTimeout=10 root@"$host_ip" "pct set $vmid --net0 '$net_config'"; then
        log_success "  Network configuration updated"
        
        # Set DNS
        ssh -o ConnectTimeout=5 root@"$host_ip" "pct set $vmid --nameserver '8.8.8.8 8.8.4.4'" 2>/dev/null || log_warn "  Warning: Failed to set DNS"
        
        # Start container if it was running
        if [ "$was_running" = true ]; then
            log_info "  Starting container..."
            ssh -o ConnectTimeout=10 root@"$host_ip" "pct start $vmid" 2>/dev/null || log_warn "  Warning: Failed to start container"
            sleep 5
        fi
        
        # Verify new IP
        if [ "$was_running" = true ]; then
            actual_ip=$(ssh -o ConnectTimeout=5 root@"$host_ip" "pct exec $vmid -- hostname -I 2>/dev/null | awk '{print \$1}'" 2>/dev/null || echo "")
            if [ "$actual_ip" = "$new_ip" ]; then
                log_success "  ✓ Verified: Container is using $new_ip"
                success_count=$((success_count + 1))
            else
                log_warn "  ⚠ Warning: Container IP is $actual_ip (expected $new_ip)"
                success_count=$((success_count + 1))
            fi
        else
            log_success "  ✓ Configuration updated (container was stopped)"
            success_count=$((success_count + 1))
        fi
    else
        log_error "  ✗ Failed to configure static IP"
        fail_count=$((fail_count + 1))
        
        # Try to restart if it was running
        if [ "$was_running" = true ]; then
            log_info "  Attempting to restart container..."
            ssh -o ConnectTimeout=10 root@"$host_ip" "pct start $vmid" 2>/dev/null || true
        fi
    fi
    
    echo ""
done

echo "=== Conversion Complete ===" | tee -a "$LOG_FILE"
echo "Successful: $success_count" | tee -a "$LOG_FILE"
echo "Failed: $fail_count" | tee -a "$LOG_FILE"
echo ""
echo "Log file: $LOG_FILE"

if [ $fail_count -gt 0 ]; then
    log_error "Some conversions failed. Check the log file for details."
    exit 1
else
    log_success "All conversions completed successfully!"
    exit 0
fi
