#!/bin/bash

# Fix Network Issues for NPMplus Container
# Diagnoses and resolves network connectivity problems

set -euo pipefail

CONTAINER_ID="10233"
NODE="r630-01"

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

echo "=========================================="
echo "Fix Network Issues for NPMplus Container"
echo "=========================================="
echo ""

# Step 1: Check DNS
echo -e "${BLUE}Step 1: Checking DNS configuration...${NC}"
DNS_SERVERS=$(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} -- cat /etc/resolv.conf 2>&1 | grep nameserver | head -3'" 2>&1)

echo "DNS servers:"
echo "$DNS_SERVERS"

if [ -z "$DNS_SERVERS" ] || ! echo "$DNS_SERVERS" | grep -q "192.168.11.1\|8.8.8.8\|1.1.1.1"; then
    echo -e "${YELLOW}⚠️  DNS may not be configured correctly${NC}"
    echo "Fixing DNS..."
    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 2>&1'" 2>&1
    echo -e "${GREEN}✅ DNS configured${NC}"
else
    echo -e "${GREEN}✅ DNS configured correctly${NC}"
fi

# Step 2: Test DNS resolution
echo ""
echo -e "${BLUE}Step 2: 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} -- nslookup registry-1.docker.io 2>&1 | grep -A 2 \"Name:\" | head -3'" 2>&1)

if echo "$DNS_TEST" | grep -q "registry-1.docker.io"; then
    echo -e "${GREEN}✅ DNS resolution working${NC}"
else
    echo -e "${RED}❌ DNS resolution failed${NC}"
    echo "Trying to fix..."
    # Restart 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
    echo "Container restarted, testing again..."
fi

# Step 3: Test internet connectivity
echo ""
echo -e "${BLUE}Step 3: Testing internet connectivity...${NC}"
PING_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 "$PING_TEST" | grep -q "0% packet loss"; then
    echo -e "${GREEN}✅ Internet connectivity working${NC}"
else
    echo -e "${RED}❌ Internet connectivity failed${NC}"
    echo "Checking 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 192.168.11.1 2>&1 | tail -3'" 2>&1)
    
    if echo "$GATEWAY_TEST" | grep -q "0% packet loss"; then
        echo -e "${GREEN}✅ Gateway reachable${NC}"
        echo -e "${YELLOW}⚠️  Internet access may be blocked by firewall${NC}"
    else
        echo -e "${RED}❌ Gateway not reachable${NC}"
        echo "Checking container network config..."
    fi
fi

# Step 4: Test Docker Hub connectivity
echo ""
echo -e "${BLUE}Step 4: 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} -- curl -s --connect-timeout 10 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"
    
    # Try with HTTP instead of HTTPS
    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} -- curl -s --connect-timeout 10 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}⚠️  HTTPS blocked, but HTTP works${NC}"
    else
        echo -e "${RED}❌ Both HTTP and HTTPS failed${NC}"
    fi
fi

# Step 5: Check container firewall
echo ""
echo -e "${BLUE}Step 5: Checking container firewall...${NC}"
FIREWALL_STATUS=$(ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
  "ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@${NODE} \
    'pct config ${CONTAINER_ID} | grep -i firewall 2>&1'" 2>&1)

if echo "$FIREWALL_STATUS" | grep -qi "firewall.*1\|firewall.*yes"; then
    echo -e "${YELLOW}⚠️  Container firewall is enabled${NC}"
    echo "This may block outbound connections"
else
    echo -e "${GREEN}✅ Container firewall is disabled${NC}"
fi

# Step 6: Check UDM Pro firewall rules
echo ""
echo -e "${BLUE}Step 6: Checking UDM Pro firewall...${NC}"
echo "Note: UDM Pro firewall may block outbound connections"
echo "Check UDM Pro Web UI → Firewall Rules for outbound restrictions"

# Step 7: Test from Proxmox host
echo ""
echo -e "${BLUE}Step 7: Testing from Proxmox host...${NC}"
HOST_TEST=$(ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
  "ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@${NODE} \
    'curl -s --connect-timeout 10 https://registry-1.docker.io/v2/ 2>&1 | head -3'" 2>&1)

if echo "$HOST_TEST" | grep -q "docker.io\|registry"; then
    echo -e "${GREEN}✅ Proxmox host can reach Docker Hub${NC}"
    echo -e "${YELLOW}⚠️  Issue is container-specific${NC}"
else
    echo -e "${RED}❌ Proxmox host also cannot reach Docker Hub${NC}"
    echo -e "${YELLOW}⚠️  Network issue at host level${NC}"
fi

# Step 8: Summary and recommendations
echo ""
echo "=========================================="
echo "Network Diagnostic Summary"
echo "=========================================="
echo ""
echo "Issues found and fixes applied:"
echo "  - DNS configuration checked"
echo "  - Internet connectivity tested"
echo "  - Docker Hub accessibility tested"
echo ""
echo "If Docker Hub is still not accessible:"
echo "  1. Check UDM Pro firewall rules for outbound restrictions"
echo "  2. Try pulling image from Proxmox host and importing"
echo "  3. Use alternative Docker registry if available"
echo ""
