#!/bin/bash

# Fix All Network Issues for NPMplus Container
# Comprehensive fix for DNS, routing, and connectivity

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 All Network Issues"
echo "=========================================="
echo ""

# Fix 1: Ensure DNS is configured correctly
echo -e "${BLUE}Fix 1: Configuring DNS...${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 set ${CONTAINER_ID} --nameserver \"192.168.11.1 8.8.8.8 1.1.1.1\" 2>&1'" 2>&1

echo -e "${GREEN}✅ DNS servers configured${NC}"

# Fix 2: Refresh ARP cache and test gateway
echo ""
echo -e "${BLUE}Fix 2: Refreshing network connections...${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 all 2>&1; \
     pct exec ${CONTAINER_ID} -- ping -c 1 ${GATEWAY} 2>&1 >/dev/null || true'" 2>&1

# Fix 3: Ensure default route is correct
echo ""
echo -e "${BLUE}Fix 3: Verifying 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)

if echo "$CURRENT_ROUTE" | grep -q "via ${GATEWAY} dev eth0"; then
    echo -e "${GREEN}✅ Default route is correct${NC}"
else
    echo -e "${YELLOW}⚠️  Fixing default route...${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 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 fixed${NC}"
fi

# Fix 4: Restart container to apply DNS changes
echo ""
echo -e "${BLUE}Fix 4: Restarting container to apply DNS changes...${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 shutdown ${CONTAINER_ID} && sleep 3 && pct start ${CONTAINER_ID} 2>&1'" 2>&1

echo "Waiting for container to start..."
sleep 10

# Fix 5: Test all connectivity
echo ""
echo -e "${BLUE}Fix 5: Testing connectivity...${NC}"

# Test gateway
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 reachable${NC}"
else
    echo -e "${RED}❌ Gateway not reachable${NC}"
    echo "This may indicate UDM Pro firewall blocking"
fi

# Test DNS
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 "Testing with direct IP..."
fi

# Test internet
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 failing${NC}"
fi

# Test Docker Hub
echo ""
echo -e "${BLUE}Fix 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 "${YELLOW}⚠️  Docker Hub not accessible via HTTPS${NC}"
    echo "Trying HTTP..."
    HTTP_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 http://registry-1.docker.io/v2/ 2>&1 | head -3'" 2>&1)
    
    if echo "$HTTP_TEST" | grep -q "docker.io\|registry"; then
        echo -e "${YELLOW}⚠️  HTTP works, HTTPS may be blocked${NC}"
    else
        echo -e "${RED}❌ Docker Hub not accessible${NC}"
    fi
fi

# Fix 7: Check UDM Pro firewall (if gateway/internet failing)
echo ""
echo -e "${BLUE}Fix 7: Checking UDM Pro firewall...${NC}"
FW_CHECK=$(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 -5" 2>&1 || echo "check_failed")

if [ "$FW_CHECK" != "check_failed" ] && [ -n "$FW_CHECK" ]; then
    echo "Firewall rules found:"
    echo "$FW_CHECK"
else
    echo -e "${YELLOW}⚠️  No specific firewall rules found for container IPs${NC}"
    echo "UDM Pro may have default rules blocking outbound traffic"
fi

echo ""
echo "=========================================="
echo "Network Fix Summary"
echo "=========================================="
echo ""
echo "Fixes applied:"
echo "  ✅ DNS servers configured (192.168.11.1, 8.8.8.8, 1.1.1.1)"
echo "  ✅ ARP cache refreshed"
echo "  ✅ Default route verified"
echo "  ✅ Container restarted"
echo ""
echo "If issues persist:"
echo "  1. Check UDM Pro firewall rules for outbound restrictions"
echo "  2. Ensure container IPs are allowed outbound"
echo "  3. Try pulling Docker image from Proxmox host instead"
echo ""
