#!/bin/bash
# Configure NPMplus proxy host for cross-all.defi-oracle.io
# This script provides instructions and checks for NPMplus configuration

set -euo pipefail

NPMPLUS_HOST="${1:-192.168.11.11}"
NPMPLUS_VMID="${2:-10233}"
BRIDGE_VM_IP="${3:-192.168.11.211}"
DOMAIN="cross-all.defi-oracle.io"

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

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

echo ""
log_info "═══════════════════════════════════════════════════════════"
log_info "  CONFIGURING NPMPLUS FOR $DOMAIN"
log_info "═══════════════════════════════════════════════════════════"
echo ""

# Step 1: Check NPMplus accessibility
log_info "Step 1: Checking NPMplus accessibility..."
if ssh -o ConnectTimeout=10 root@"$NPMPLUS_HOST" "pct exec $NPMPLUS_VMID -- docker ps | grep -q npmplus" 2>/dev/null; then
    log_success "NPMplus container is running"
else
    log_error "NPMplus container not found or not running"
    exit 1
fi

# Step 2: Check if proxy host already exists
log_info "Step 2: Checking if proxy host already exists..."
EXISTING=$(ssh -o ConnectTimeout=10 root@"$NPMPLUS_HOST" \
    "pct exec $NPMPLUS_VMID -- docker exec npmplus nginx -T 2>/dev/null | grep -A 5 'server_name.*$DOMAIN' | head -10" 2>/dev/null || echo "")

if [ -n "$EXISTING" ]; then
    log_warn "Proxy host for $DOMAIN already exists in NPMplus"
    echo "$EXISTING" | head -10
    echo ""
    read -p "Do you want to update it? (y/N): " -n 1 -r
    echo ""
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        log_info "Skipping NPMplus configuration"
        exit 0
    fi
fi

# Step 3: Check bridge VM accessibility
log_info "Step 3: Verifying bridge VM accessibility..."
if curl -s -o /dev/null -w "%{http_code}" --connect-timeout 3 "http://$BRIDGE_VM_IP/" | grep -q "200"; then
    log_success "Bridge VM is accessible at http://$BRIDGE_VM_IP/"
else
    log_error "Bridge VM not accessible at http://$BRIDGE_VM_IP/"
    exit 1
fi

echo ""
log_info "═══════════════════════════════════════════════════════════"
log_info "  MANUAL NPMPLUS CONFIGURATION REQUIRED"
log_info "═══════════════════════════════════════════════════════════"
echo ""

log_info "NPMplus must be configured manually via web interface:"
echo ""
echo "1. Access NPMplus Dashboard:"
echo "   https://[NPMplus-IP]:81"
echo ""
echo "2. Create Proxy Host:"
echo "   - Click 'Proxy Hosts' → 'Add Proxy Host'"
echo ""
echo "3. Details Tab:"
echo "   Domain Names: $DOMAIN"
echo "   Scheme: http"
echo "   Forward Hostname/IP: $BRIDGE_VM_IP"
echo "   Forward Port: 80"
echo "   ✅ Cache Assets"
echo "   ✅ Block Common Exploits"
echo "   ✅ Websockets Support"
echo ""
echo "4. SSL Tab:"
echo "   - Request new SSL Certificate (Let's Encrypt)"
echo "   ✅ Force SSL"
echo "   ✅ HTTP/2 Support"
echo "   ✅ HSTS Enabled"
echo ""
echo "5. Save and Test"
echo ""

# Step 4: Generate configuration file for reference
CONFIG_FILE="/tmp/npmplus-bridge-dapp-config.json"
cat > "$CONFIG_FILE" << EOF
{
  "domain_names": ["$DOMAIN"],
  "forward_scheme": "http",
  "forward_host": "$BRIDGE_VM_IP",
  "forward_port": 80,
  "cache_assets": true,
  "block_exploits": true,
  "websockets_support": true,
  "ssl_forced": true,
  "http2_support": true,
  "hsts_enabled": true,
  "hsts_subdomains": false,
  "access_list_id": "0",
  "certificate_id": 0,
  "advanced_config": "",
  "locations": [],
  "custom_nginx": ""
}
EOF

log_info "Configuration template saved to: $CONFIG_FILE"
log_info "This can be used for API-based configuration if NPMplus API is enabled"
echo ""

# Step 5: Wait for user to configure
log_info "Step 5: Waiting for NPMplus configuration..."
echo ""
read -p "Press Enter after configuring NPMplus proxy host, or Ctrl+C to skip..."
echo ""

# Step 6: Verify configuration
log_info "Step 6: Verifying NPMplus configuration..."
sleep 2

VERIFY=$(ssh -o ConnectTimeout=10 root@"$NPMPLUS_HOST" \
    "pct exec $NPMPLUS_VMID -- docker exec npmplus nginx -T 2>/dev/null | grep -A 10 'server_name.*$DOMAIN' | head -15" 2>/dev/null || echo "")

if [ -n "$VERIFY" ]; then
    log_success "Proxy host configuration found in NPMplus!"
    echo "$VERIFY" | head -15
    echo ""
    
    # Test domain access
    log_info "Testing domain access..."
    HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 5 "http://$DOMAIN/" 2>/dev/null || echo "000")
    HTTPS_CODE=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 5 "https://$DOMAIN/" 2>/dev/null || echo "000")
    
    if [ "$HTTP_CODE" = "200" ] || [ "$HTTPS_CODE" = "200" ]; then
        log_success "Domain is accessible! (HTTP: $HTTP_CODE, HTTPS: $HTTPS_CODE)"
    else
        log_warn "Domain not yet accessible (HTTP: $HTTP_CODE, HTTPS: $HTTPS_CODE)"
        log_info "This may be due to DNS propagation or SSL certificate issuance"
    fi
else
    log_warn "Proxy host configuration not found in NPMplus"
    log_info "Please ensure you've configured the proxy host manually"
fi

echo ""
log_success "═══════════════════════════════════════════════════════════"
log_success "  NPMPLUS CONFIGURATION CHECK COMPLETE"
log_success "═══════════════════════════════════════════════════════════"
echo ""

rm -f "$CONFIG_FILE"
