#!/bin/bash

# Re-add net1 to NPMplus container to restore functionality
# This restores access on 192.168.11.167 while we investigate Docker container issues

set -euo pipefail

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

echo "=========================================="
echo "Re-adding net1 to NPMplus Container"
echo "=========================================="
echo ""

# Check current network config
echo "Current network configuration:"
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 net'" 2>&1

echo ""
echo "Re-adding net1 interface..."
echo "This will require container restart."

# Re-add net1
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} --net1 name=eth1,bridge=vmbr0,ip=192.168.11.167/24 2>&1'" 2>&1

echo ""
echo "Restarting container to apply 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 5 && pct start ${CONTAINER_ID} 2>&1'" 2>&1

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

echo ""
echo "Verifying network configuration:"
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 addr show 2>&1 | grep -A 3 \"inet.*192.168.11\"'" 2>&1

echo ""
echo "Testing 192.168.11.167 accessibility..."
sleep 5
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 "✅ 192.168.11.167 is accessible (HTTP ${HTTP_167})"
else
  echo "⚠️  192.168.11.167 returned HTTP ${HTTP_167}"
fi

echo ""
echo "=========================================="
echo "Net1 re-added"
echo "=========================================="
echo ""
echo "Next steps:"
echo "1. Update UDM Pro port forwarding to use 192.168.11.167"
echo "2. Investigate why NPMplus container is unhealthy"
echo "3. Once Docker container is fixed, can remove net1 again"
