#!/bin/bash
# Diagnose Incus network issues
# Usage: ./diagnose-network.sh [container-name]

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"
CONTAINER="${1:-veza-infra}"

echo -e "${BLUE}🔍 Diagnosing Incus network issues${NC}"
echo ""

# 1. Host IP forwarding
echo -e "${BLUE}1. Host IP Forwarding:${NC}"
IP_FORWARD=$(cat /proc/sys/net/ipv4/ip_forward 2>/dev/null || echo "0")
if [ "${IP_FORWARD}" = "1" ]; then
    echo -e "${GREEN}   ✅ Enabled${NC}"
else
    echo -e "${RED}   ❌ Disabled (NAT will not work!)${NC}"
    echo "   Fix: echo 1 | sudo tee /proc/sys/net/ipv4/ip_forward"
fi

# 2. Network configuration
echo -e "${BLUE}2. Network Configuration (${NETWORK}):${NC}"
if incus network show ${NETWORK} >/dev/null 2>&1; then
    NAT=$(incus network show ${NETWORK} | grep "ipv4.nat" | awk '{print $2}' || echo "false")
    DHCP=$(incus network show ${NETWORK} | grep "ipv4.dhcp" | awk '{print $2}' || echo "false")
    
    if [ "${NAT}" = "\"true\"" ]; then
        echo -e "${GREEN}   ✅ NAT: Enabled${NC}"
    else
        echo -e "${RED}   ❌ NAT: Disabled${NC}"
    fi
    
    if [ "${DHCP}" = "\"true\"" ]; then
        echo -e "${GREEN}   ✅ DHCP: Enabled${NC}"
    else
        echo -e "${YELLOW}   ⚠️  DHCP: Disabled${NC}"
    fi
else
    echo -e "${RED}   ❌ Network does not exist${NC}"
fi

# 3. Container network state
if incus list -c n --format csv 2>/dev/null | grep -q "^${CONTAINER}$"; then
    echo -e "${BLUE}3. Container Network State (${CONTAINER}):${NC}"
    
    # IP address
    CONTAINER_IP=$(incus exec ${CONTAINER} -- ip addr show eth0 2>/dev/null | grep "inet " | awk '{print $2}' | cut -d'/' -f1 || echo "none")
    if [ "${CONTAINER_IP}" != "none" ] && [ -n "${CONTAINER_IP}" ]; then
        echo -e "${GREEN}   ✅ IP: ${CONTAINER_IP}${NC}"
    else
        echo -e "${RED}   ❌ IP: Not configured${NC}"
    fi
    
    # Default route
    DEFAULT_ROUTE=$(incus exec ${CONTAINER} -- ip route | grep default || echo "none")
    if [ "${DEFAULT_ROUTE}" != "none" ]; then
        if echo "${DEFAULT_ROUTE}" | grep -q "10.10.10.1"; then
            echo -e "${GREEN}   ✅ Default route: ${DEFAULT_ROUTE}${NC}"
        else
            echo -e "${YELLOW}   ⚠️  Default route: ${DEFAULT_ROUTE}${NC}"
        fi
    else
        echo -e "${RED}   ❌ Default route: Missing${NC}"
    fi
    
    # DNS
    DNS=$(incus exec ${CONTAINER} -- cat /etc/resolv.conf 2>/dev/null | grep nameserver | head -1 || echo "none")
    if [ "${DNS}" != "none" ]; then
        echo -e "${GREEN}   ✅ DNS: ${DNS}${NC}"
    else
        echo -e "${RED}   ❌ DNS: Not configured${NC}"
    fi
    
    # Connectivity tests
    echo -e "${BLUE}4. Connectivity Tests:${NC}"
    
    # Gateway
    if incus exec ${CONTAINER} -- ping -c 1 -W 1 10.10.10.1 >/dev/null 2>&1; then
        echo -e "${GREEN}   ✅ Gateway (10.10.10.1): Reachable${NC}"
    else
        echo -e "${RED}   ❌ Gateway (10.10.10.1): Not reachable${NC}"
    fi
    
    # Internet
    if incus exec ${CONTAINER} -- ping -c 1 -W 1 8.8.8.8 >/dev/null 2>&1; then
        echo -e "${GREEN}   ✅ Internet (8.8.8.8): Reachable${NC}"
    else
        echo -e "${RED}   ❌ Internet (8.8.8.8): Not reachable${NC}"
    fi
    
    # DNS resolution
    if incus exec ${CONTAINER} -- getent hosts google.com >/dev/null 2>&1; then
        echo -e "${GREEN}   ✅ DNS (google.com): Working${NC}"
    else
        echo -e "${RED}   ❌ DNS (google.com): Failed${NC}"
    fi
else
    echo -e "${YELLOW}   ⚠️  Container ${CONTAINER} does not exist${NC}"
fi

# 5. Bridge interface
echo -e "${BLUE}5. Bridge Interface:${NC}"
BRIDGE=$(ip -br link show | grep -E "incus|veza" | head -1 | awk '{print $1}' || echo "none")
if [ "${BRIDGE}" != "none" ]; then
    echo -e "${GREEN}   ✅ Bridge: ${BRIDGE}${NC}"
    BRIDGE_STATE=$(ip link show ${BRIDGE} 2>/dev/null | grep -o "state [A-Z]*" | awk '{print $2}' || echo "unknown")
    if [ "${BRIDGE_STATE}" = "UP" ]; then
        echo -e "${GREEN}   ✅ Bridge state: UP${NC}"
    else
        echo -e "${RED}   ❌ Bridge state: ${BRIDGE_STATE}${NC}"
    fi
else
    echo -e "${YELLOW}   ⚠️  Bridge interface not found${NC}"
fi

echo ""
echo -e "${BLUE}=== Summary ===${NC}"
echo "To fix network issues, run:"
echo "  ./fix-network.sh ${CONTAINER}"
echo ""
echo "To fix all containers:"
echo "  ./fix-all-containers-network.sh"
