#!/bin/bash

# Fix IP Conflict: Reassign VMID 10234 from 192.168.11.167 to 192.168.11.168
# This resolves the conflict with VMID 10233 (npmplus)

set -euo pipefail

CONFLICT_VMID="10234"
CONFLICT_NODE="r630-02"
OLD_IP="192.168.11.167"
NEW_IP="192.168.11.168"
GATEWAY="192.168.11.1"

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

echo "=========================================="
echo "Fix IP Conflict: VMID 10234"
echo "=========================================="
echo ""
echo "Current conflict:"
echo "  - VMID 10233 (npmplus) on r630-01: ${OLD_IP}"
echo "  - VMID 10234 (npmplus-secondary) on r630-02: ${OLD_IP}"
echo ""
echo "Resolution:"
echo "  - VMID 10233: Keep ${OLD_IP}"
echo "  - VMID 10234: Reassign to ${NEW_IP}"
echo ""

# Step 1: Verify current configuration
echo -e "${BLUE}Step 1: Verifying current configuration...${NC}"
CURRENT_CONFIG=$(ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
  "ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@${CONFLICT_NODE} \
    'pct config ${CONFLICT_VMID} | grep net0'" 2>&1)

echo "Current config: ${CURRENT_CONFIG}"

if ! echo "$CURRENT_CONFIG" | grep -q "ip=${OLD_IP}"; then
    echo -e "${YELLOW}⚠️  VMID ${CONFLICT_VMID} is not using ${OLD_IP}${NC}"
    echo "Current IP: $(echo "$CURRENT_CONFIG" | grep -oE 'ip=[0-9.]+' | cut -d= -f2)"
    read -p "Continue anyway? (y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "Aborted."
        exit 1
    fi
fi

# Step 2: Check if new IP is available
echo ""
echo -e "${BLUE}Step 2: Checking if ${NEW_IP} is available...${NC}"
IP_IN_USE=$(ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
  "for node in r630-01 r630-02; do ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@\$node 'for vm in \$(pct list 2>/dev/null | tail -n +2 | awk \"{print \\\$1}\"); do pct config \$vm 2>/dev/null | grep -q \"ip=${NEW_IP}\" && echo \"\$node:VMID \$vm\" || true; done' 2>&1; done" 2>&1)

if [ -n "$IP_IN_USE" ]; then
    echo -e "${RED}❌ ${NEW_IP} is already in use:${NC}"
    echo "$IP_IN_USE"
    echo ""
    read -p "Choose different IP (or press Enter to abort): " NEW_IP
    if [ -z "$NEW_IP" ]; then
        echo "Aborted."
        exit 1
    fi
    echo "Using ${NEW_IP} instead"
fi

# Step 3: Stop container
echo ""
echo -e "${BLUE}Step 3: Stopping container...${NC}"
ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
  "ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@${CONFLICT_NODE} \
    'pct shutdown ${CONFLICT_VMID} && sleep 3'" 2>&1

# Step 4: Get current MAC address
echo ""
echo -e "${BLUE}Step 4: Getting current MAC address...${NC}"
CURRENT_MAC=$(echo "$CURRENT_CONFIG" | grep -oE 'hwaddr=[^,]+' | cut -d= -f2)
echo "Current MAC: ${CURRENT_MAC}"

# Step 5: Update IP address
echo ""
echo -e "${BLUE}Step 5: Updating IP address to ${NEW_IP}...${NC}"
ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
  "ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@${CONFLICT_NODE} \
    'pct set ${CONFLICT_VMID} --net0 name=eth0,bridge=vmbr0,gw=${GATEWAY},hwaddr=${CURRENT_MAC},ip=${NEW_IP}/24,type=veth 2>&1'" 2>&1

# Step 6: Verify configuration
echo ""
echo -e "${BLUE}Step 6: Verifying new configuration...${NC}"
NEW_CONFIG=$(ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
  "ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@${CONFLICT_NODE} \
    'pct config ${CONFLICT_VMID} | grep net0'" 2>&1)

echo "New config: ${NEW_CONFIG}"

if echo "$NEW_CONFIG" | grep -q "ip=${NEW_IP}"; then
    echo -e "${GREEN}✅ IP address updated successfully${NC}"
else
    echo -e "${RED}❌ IP address update failed${NC}"
    exit 1
fi

# Step 7: Start container
echo ""
echo -e "${BLUE}Step 7: Starting container...${NC}"
ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
  "ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@${CONFLICT_NODE} \
    'pct start ${CONFLICT_VMID} 2>&1'" 2>&1

sleep 5

# Step 8: Verify IP is active
echo ""
echo -e "${BLUE}Step 8: Verifying IP is active in container...${NC}"
ACTIVE_IP=$(ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
  "ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@${CONFLICT_NODE} \
    'pct exec ${CONFLICT_VMID} -- ip addr show eth0 2>&1 | grep \"inet.*${NEW_IP}\"'" 2>&1)

if [ -n "$ACTIVE_IP" ]; then
    echo -e "${GREEN}✅ IP ${NEW_IP} is active in container${NC}"
else
    echo -e "${YELLOW}⚠️  IP may not be active yet, waiting 5 more seconds...${NC}"
    sleep 5
    ACTIVE_IP=$(ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
      "ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@${CONFLICT_NODE} \
        'pct exec ${CONFLICT_VMID} -- ip addr show eth0 2>&1 | grep \"inet.*${NEW_IP}\"'" 2>&1)
    if [ -n "$ACTIVE_IP" ]; then
        echo -e "${GREEN}✅ IP ${NEW_IP} is now active${NC}"
    else
        echo -e "${RED}❌ IP ${NEW_IP} is not active${NC}"
    fi
fi

# Step 9: Verify no conflicts remain
echo ""
echo -e "${BLUE}Step 9: Verifying no IP conflicts remain...${NC}"
CONFLICTS=$(ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
  "for node in r630-01 r630-02; do ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@\$node 'for vm in \$(pct list 2>/dev/null | tail -n +2 | awk \"{print \\\$1}\"); do ip=\$(pct config \$vm 2>/dev/null | grep -oE \"ip=192.168.11.167/\" | cut -d= -f2 | cut -d/ -f1); if [ -n \"\$ip\" ]; then echo \"\$node:VMID \$vm: \$ip\"; fi; done' 2>&1; done" 2>&1)

CONFLICT_COUNT=$(echo "$CONFLICTS" | wc -l)
if [ "$CONFLICT_COUNT" -eq 1 ]; then
    echo -e "${GREEN}✅ No conflicts - only one container using 192.168.11.167${NC}"
    echo "Remaining: $CONFLICTS"
else
    echo -e "${RED}❌ Conflict still exists:${NC}"
    echo "$CONFLICTS"
fi

echo ""
echo "=========================================="
echo "IP Conflict Resolution Complete"
echo "=========================================="
echo ""
echo "Summary:"
echo "  ✅ VMID 10234 reassigned from ${OLD_IP} to ${NEW_IP}"
echo "  ✅ VMID 10233 remains on ${OLD_IP}"
echo ""
echo "Next steps:"
echo "  1. Verify UDM Pro sees correct MAC for 192.168.11.167"
echo "  2. Update UDM Pro port forwarding if needed"
echo "  3. Test NPMplus connectivity"
echo ""
