#!/bin/bash

# Fix Container Network Issues
# Resolves gateway connectivity and internet access problems

set -euo pipefail

CONTAINER_ID="10233"
NODE="r630-01"
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 Container Network Issues"
echo "=========================================="
echo ""

# Issue 1: Fix default route
echo -e "${BLUE}Issue 1: Fixing default route...${NC}"
CURRENT_ROUTE=$(ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
  "ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@${NODE} \
    'pct exec ${CONTAINER_ID} -- ip route show default 2>&1'" 2>&1)

echo "Current default route: $CURRENT_ROUTE"

# Check if route uses correct interface
if echo "$CURRENT_ROUTE" | grep -q "eth0"; then
    echo -e "${GREEN}✅ Default route uses eth0${NC}"
else
    echo -e "${YELLOW}⚠️  Default route may need fixing${NC}"
    # Add route via eth0
    ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
      "ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@${NODE} \
        'pct exec ${CONTAINER_ID} -- ip route del default 2>/dev/null; pct exec ${CONTAINER_ID} -- ip route add default via ${GATEWAY} dev eth0 2>&1'" 2>&1
    echo -e "${GREEN}✅ Default route updated${NC}"
fi

# Issue 2: Flush ARP cache and refresh
echo ""
echo -e "${BLUE}Issue 2: Refreshing ARP cache...${NC}"
ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
  "ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@${NODE} \
    'pct exec ${CONTAINER_ID} -- ip neigh flush dev eth0 2>&1; \
     pct exec ${CONTAINER_ID} -- ping -c 1 ${GATEWAY} 2>&1 >/dev/null || true'" 2>&1

# Issue 3: Test gateway connectivity
echo ""
echo -e "${BLUE}Issue 3: Testing gateway connectivity...${NC}"
GATEWAY_TEST=$(ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
  "ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@${NODE} \
    'pct exec ${CONTAINER_ID} -- ping -c 2 -W 2 ${GATEWAY} 2>&1 | tail -3'" 2>&1)

if echo "$GATEWAY_TEST" | grep -q "0% packet loss"; then
    echo -e "${GREEN}✅ Gateway is reachable${NC}"
else
    echo -e "${RED}❌ Gateway still not reachable${NC}"
    echo "This may be a UDM Pro firewall issue blocking outbound traffic"
    echo ""
    echo "Checking UDM Pro firewall rules..."
    
    # Check UDM Pro firewall
    FW_RULES=$(sshpass -p 'm0MFXHdgMFKGB2l3bO4' ssh -o ConnectTimeout=10 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR OQmQuS@192.168.11.1 \
      "sudo iptables -L FORWARD -n -v 2>&1 | grep -E '192.168.11.166|192.168.11.167' | head -10" 2>&1)
    
    if [ -z "$FW_RULES" ]; then
        echo -e "${YELLOW}⚠️  No specific firewall rules found for container IPs${NC}"
        echo "UDM Pro may have default deny rules blocking outbound traffic"
    else
        echo "Firewall rules:"
        echo "$FW_RULES"
    fi
fi

# Issue 4: Test DNS
echo ""
echo -e "${BLUE}Issue 4: Testing DNS resolution...${NC}"
DNS_TEST=$(ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
  "ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@${NODE} \
    'pct exec ${CONTAINER_ID} -- timeout 5 nslookup registry-1.docker.io 2>&1 | head -5'" 2>&1)

if echo "$DNS_TEST" | grep -q "registry-1.docker.io\|Address:"; then
    echo -e "${GREEN}✅ DNS resolution working${NC}"
else
    echo -e "${RED}❌ DNS resolution still failing${NC}"
    echo "Trying alternative DNS servers..."
    
    # Add Google DNS as backup
    ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
      "ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@${NODE} \
        'pct set ${CONTAINER_ID} --nameserver \"192.168.11.1 8.8.8.8\" 2>&1'" 2>&1
    
    echo -e "${GREEN}✅ Added backup DNS servers${NC}"
    echo "Restarting container to apply DNS changes..."
    ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
      "ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@${NODE} \
        'pct shutdown ${CONTAINER_ID} && sleep 3 && pct start ${CONTAINER_ID} 2>&1'" 2>&1
    sleep 5
fi

# Issue 5: Test internet connectivity
echo ""
echo -e "${BLUE}Issue 5: Testing internet connectivity...${NC}"
INTERNET_TEST=$(ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
  "ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@${NODE} \
    'pct exec ${CONTAINER_ID} -- ping -c 2 -W 2 8.8.8.8 2>&1 | tail -3'" 2>&1)

if echo "$INTERNET_TEST" | grep -q "0% packet loss"; then
    echo -e "${GREEN}✅ Internet connectivity working${NC}"
else
    echo -e "${RED}❌ Internet connectivity still failing${NC}"
    echo "This indicates UDM Pro firewall is blocking outbound traffic"
fi

# Issue 6: Test Docker Hub
echo ""
echo -e "${BLUE}Issue 6: Testing Docker Hub connectivity...${NC}"
DOCKER_TEST=$(ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
  "ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@${NODE} \
    'pct exec ${CONTAINER_ID} -- timeout 10 curl -s https://registry-1.docker.io/v2/ 2>&1 | head -3'" 2>&1)

if echo "$DOCKER_TEST" | grep -q "docker.io\|registry"; then
    echo -e "${GREEN}✅ Docker Hub accessible${NC}"
else
    echo -e "${RED}❌ Docker Hub not accessible${NC}"
    echo "Response: $DOCKER_TEST"
fi

echo ""
echo "=========================================="
echo "Network Fix Summary"
echo "=========================================="
echo ""
echo "If gateway/internet still not working:"
echo "  1. Check UDM Pro firewall rules for outbound restrictions"
echo "  2. Ensure container IPs (192.168.11.166/167) are allowed outbound"
echo "  3. Check UDM Pro Web UI → Firewall Rules"
echo ""
