#!/bin/bash

# Fix NPMplus Docker Network Mode
# Changes from host network to bridge network with port mapping
# This fixes the issue where NPMplus is only accessible on 192.168.11.167

set -euo pipefail

CONTAINER_ID="10233"
NODE="r630-01"
DOCKER_CONTAINER="npmplus"
IMAGE="zoeyvid/npmplus:latest"

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

echo "=========================================="
echo "Fix NPMplus Docker Network Mode"
echo "=========================================="
echo ""

# Step 1: Check current configuration
echo -e "${BLUE}Step 1: Checking current Docker container configuration...${NC}"
CURRENT_NETWORK=$(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} -- docker inspect ${DOCKER_CONTAINER} --format \"{{.HostConfig.NetworkMode}}\" 2>&1'" 2>&1)

echo "Current network mode: ${CURRENT_NETWORK}"

if [ "$CURRENT_NETWORK" != "host" ]; then
  echo -e "${YELLOW}⚠️  Container is not using host network mode. Current mode: ${CURRENT_NETWORK}${NC}"
  read -p "Continue anyway? (y/N): " -n 1 -r
  echo
  if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Aborted."
    exit 1
  fi
fi

# Step 2: Check data volumes
echo -e "${BLUE}Step 2: Checking data volumes...${NC}"
VOLUMES=$(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} -- docker inspect ${DOCKER_CONTAINER} --format \"{{range .Mounts}}{{.Source}}:{{.Destination}} {{end}}\" 2>&1'" 2>&1)

echo "Data volumes: ${VOLUMES}"

# Step 3: Stop Docker container
echo -e "${BLUE}Step 3: Stopping Docker container...${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} -- docker stop ${DOCKER_CONTAINER} 2>&1'" 2>&1

sleep 2

# Step 4: Remove Docker container (keeping volumes)
echo -e "${BLUE}Step 4: Removing Docker container (volumes preserved)...${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} -- docker rm ${DOCKER_CONTAINER} 2>&1'" 2>&1

sleep 1

# Step 5: Recreate with bridge network
echo -e "${BLUE}Step 5: Recreating Docker container with bridge network...${NC}"

# Extract volume mounts from previous container
DATA_VOLUME="/data/npmplus"
CERT_VOLUME="/data/letsencrypt"

# Recreate container with bridge network and port mapping
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} -- docker run -d \
      --name ${DOCKER_CONTAINER} \
      --restart unless-stopped \
      --network bridge \
      -p 80:80 \
      -p 443:443 \
      -p 81:81 \
      -v ${DATA_VOLUME}:/data \
      -v ${CERT_VOLUME}:/etc/letsencrypt \
      ${IMAGE} 2>&1'" 2>&1

sleep 3

# Step 6: Verify container is running
echo -e "${BLUE}Step 6: Verifying container is running...${NC}"
CONTAINER_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 exec ${CONTAINER_ID} -- docker ps --filter name=${DOCKER_CONTAINER} --format \"{{.Status}}\" 2>&1'" 2>&1)

if [ -z "$CONTAINER_STATUS" ]; then
  echo -e "${RED}❌ Container is not running!${NC}"
  echo "Checking logs..."
  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} -- docker logs ${DOCKER_CONTAINER} --tail 50 2>&1'" 2>&1 | tail -20
  exit 1
fi

echo -e "${GREEN}✅ Container is running: ${CONTAINER_STATUS}${NC}"

# Step 7: Verify network mode
echo -e "${BLUE}Step 7: Verifying network mode...${NC}"
NEW_NETWORK=$(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} -- docker inspect ${DOCKER_CONTAINER} --format \"{{.HostConfig.NetworkMode}}\" 2>&1'" 2>&1)

echo "New network mode: ${NEW_NETWORK}"

if [ "$NEW_NETWORK" != "bridge" ]; then
  echo -e "${RED}❌ Network mode is not bridge! Current: ${NEW_NETWORK}${NC}"
  exit 1
fi

echo -e "${GREEN}✅ Network mode is bridge${NC}"

# Step 8: Verify ports are listening
echo -e "${BLUE}Step 8: Verifying ports are listening...${NC}"
sleep 5  # Give NPMplus time to start

PORTS=$(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} -- ss -tlnp 2>&1 | grep -E \":80 |:443 \" | head -4'" 2>&1)

echo "Listening ports:"
echo "$PORTS"

if echo "$PORTS" | grep -q ":80" && echo "$PORTS" | grep -q ":443"; then
  echo -e "${GREEN}✅ Ports 80 and 443 are listening${NC}"
else
  echo -e "${YELLOW}⚠️  Ports may not be fully started yet. Waiting 10 more seconds...${NC}"
  sleep 10
  PORTS=$(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} -- ss -tlnp 2>&1 | grep -E \":80 |:443 \" | head -4'" 2>&1)
  echo "$PORTS"
fi

# Step 9: Test connectivity
echo -e "${BLUE}Step 9: Testing connectivity...${NC}"

# Test on 192.168.11.166 (primary IP)
echo "Testing 192.168.11.166:80..."
HTTP_166=$(curl -s -o /dev/null -w '%{http_code}' --connect-timeout 5 http://192.168.11.166:80 2>&1 || echo "000")
if [ "$HTTP_166" = "200" ] || [ "$HTTP_166" = "301" ] || [ "$HTTP_166" = "302" ] || [ "$HTTP_166" = "308" ]; then
  echo -e "${GREEN}✅ 192.168.11.166:80 is accessible (HTTP ${HTTP_166})${NC}"
else
  echo -e "${YELLOW}⚠️  192.168.11.166:80 returned HTTP ${HTTP_166}${NC}"
fi

# Test on 192.168.11.167 (secondary IP)
echo "Testing 192.168.11.167:80..."
HTTP_167=$(curl -s -o /dev/null -w '%{http_code}' --connect-timeout 5 http://192.168.11.167:80 2>&1 || echo "000")
if [ "$HTTP_167" = "200" ] || [ "$HTTP_167" = "301" ] || [ "$HTTP_167" = "302" ] || [ "$HTTP_167" = "308" ]; then
  echo -e "${GREEN}✅ 192.168.11.167:80 is accessible (HTTP ${HTTP_167})${NC}"
else
  echo -e "${YELLOW}⚠️  192.168.11.167:80 returned HTTP ${HTTP_167}${NC}"
fi

# Step 10: Test NPMplus → VMID 5000
echo -e "${BLUE}Step 10: Testing NPMplus proxy to VMID 5000...${NC}"
PROXY_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 -H \"Host: explorer.d-bis.org\" -o /dev/null -w \"HTTP %{http_code}\" --connect-timeout 5 http://192.168.11.140:80 2>&1'" 2>&1)

if echo "$PROXY_TEST" | grep -q "200"; then
  echo -e "${GREEN}✅ NPMplus can proxy to VMID 5000 (${PROXY_TEST})${NC}"
else
  echo -e "${YELLOW}⚠️  NPMplus proxy test: ${PROXY_TEST}${NC}"
fi

echo ""
echo "=========================================="
echo "Fix Complete!"
echo "=========================================="
echo ""
echo "Summary:"
echo "- Docker network mode changed from 'host' to 'bridge'"
echo "- Ports 80, 443, and 81 are mapped"
echo "- Data volumes preserved"
echo ""
echo "Next steps:"
echo "1. Verify NPMplus dashboard: https://192.168.11.166:81"
echo "2. Test external access: curl -I https://explorer.d-bis.org"
echo "3. If 192.168.11.166 is now accessible, update UDM Pro port forwarding back to 192.168.11.166"
echo ""
