#!/bin/bash
# Fix network in all Veza containers
# Usage: ./fix-all-containers-network.sh

set -euo pipefail

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

NETWORK="veza-network"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

echo -e "${BLUE}🔧 Fixing network in all Veza containers${NC}"
echo ""

# First, fix the network infrastructure
"${SCRIPT_DIR}/fix-network.sh"

# Get all Veza containers
CONTAINERS=$(incus list veza- --format csv | cut -d',' -f1)

if [ -z "${CONTAINERS}" ]; then
    echo -e "${YELLOW}⚠️  No Veza containers found${NC}"
    exit 0
fi

echo -e "${BLUE}Fixing network in containers...${NC}"
echo ""

for CONTAINER in ${CONTAINERS}; do
    echo -e "${BLUE}--- ${CONTAINER} ---${NC}"
    
    # Get container IP from Incus
    CONTAINER_IP=$(incus list ${CONTAINER} --format csv | cut -d',' -f4 | awk '{print $1}' | head -1 || echo "")
    
    # Try to get from device config if not found
    if [ -z "${CONTAINER_IP}" ] || [ "${CONTAINER_IP}" = "" ]; then
        CONTAINER_IP=$(incus config device show ${CONTAINER} 2>/dev/null | grep "ipv4.address" | head -1 | awk '{print $2}' || echo "")
    fi
    
    # Try to get from network info
    if [ -z "${CONTAINER_IP}" ] || [ "${CONTAINER_IP}" = "" ]; then
        CONTAINER_IP=$(incus network list-leases ${NETWORK} 2>/dev/null | grep "${CONTAINER}" | awk '{print $4}' | head -1 || echo "")
    fi
    
    if [ -z "${CONTAINER_IP}" ] || [ "${CONTAINER_IP}" = "" ]; then
        echo -e "${YELLOW}   ⚠️  Could not determine IP for ${CONTAINER}, skipping...${NC}"
        continue
    fi
    
    echo -e "${BLUE}   IP: ${CONTAINER_IP}${NC}"
    
    # Fix network inside container
    if incus exec ${CONTAINER} -- bash -c "
        set -e
        # Remove any existing IP
        ip addr flush dev eth0 2>/dev/null || true
        # Add IP
        ip addr add ${CONTAINER_IP}/24 dev eth0 2>/dev/null || \
            ip addr replace ${CONTAINER_IP}/24 dev eth0
        # Remove old default route
        ip route del default 2>/dev/null || true
        # Add default route
        ip route add default via 10.10.10.1 dev eth0
        # Configure DNS
        rm -f /etc/resolv.conf
        echo 'nameserver 8.8.8.8' > /etc/resolv.conf
        echo 'nameserver 1.1.1.1' >> /etc/resolv.conf
        # Restart systemd-resolved if available
        systemctl restart systemd-resolved 2>/dev/null || true
    " 2>/dev/null; then
        echo -e "${GREEN}   ✅ Network configured${NC}"
        
        # Test connectivity
        if incus exec ${CONTAINER} -- ping -c 1 -W 1 8.8.8.8 >/dev/null 2>&1; then
            echo -e "${GREEN}   ✅ Internet connectivity OK${NC}"
        else
            echo -e "${YELLOW}   ⚠️  Internet connectivity failed${NC}"
        fi
    else
        echo -e "${RED}   ❌ Failed to configure network${NC}"
    fi
    
    echo ""
done

echo -e "${GREEN}✅ Network fix complete for all containers!${NC}"
