#!/bin/bash

# Check NPMplus configuration for explorer.d-bis.org
# Verifies if NPMplus is correctly configured to route to VMID 5000

set -euo pipefail

NPM_URL="${NPM_URL:-https://192.168.11.166:81}"
NPM_EMAIL="${NPM_EMAIL:-nsatoshi2007@hotmail.com}"
NPM_PASSWORD="${NPM_PASSWORD:-ce8219e321e1cd97bd590fb792d3caeb7e2e3b94ca7e20124acaf253f911ff72}"

echo "=========================================="
echo "NPMplus Explorer Configuration Check"
echo "=========================================="
echo "NPMplus URL: $NPM_URL"
echo "Domain: explorer.d-bis.org"
echo "Expected Target: 192.168.11.140:80 (VMID 5000)"
echo "=========================================="
echo ""

# Get auth token
echo "=== Step 1: Authenticating with NPMplus ==="
AUTH_RESPONSE=$(curl -s -k -X POST "$NPM_URL/api/tokens" \
  -H "Content-Type: application/json" \
  -d "{\"identity\":\"$NPM_EMAIL\",\"secret\":\"$NPM_PASSWORD\"}" 2>/dev/null || echo "")

if [ -z "$AUTH_RESPONSE" ] || echo "$AUTH_RESPONSE" | grep -q "error\|unauthorized"; then
    echo "❌ Failed to authenticate with NPMplus"
    echo "Response: $AUTH_RESPONSE"
    exit 1
fi

TOKEN=$(echo "$AUTH_RESPONSE" | grep -o '"token":"[^"]*' | cut -d'"' -f4 || echo "")
if [ -z "$TOKEN" ]; then
    echo "❌ Failed to extract auth token"
    exit 1
fi

echo "✅ Authenticated successfully"
echo ""

# Get proxy hosts
echo "=== Step 2: Fetching proxy host configurations ==="
PROXY_HOSTS=$(curl -s -k -X GET "$NPM_URL/api/nginx/proxy-hosts" \
  -H "Authorization: Bearer $TOKEN" 2>/dev/null || echo "")

if [ -z "$PROXY_HOSTS" ]; then
    echo "❌ Failed to fetch proxy hosts"
    exit 1
fi

echo "✅ Fetched proxy hosts"
echo ""

# Find explorer configuration
echo "=== Step 3: Checking explorer.d-bis.org configuration ==="
EXPLORER_CONFIG=$(echo "$PROXY_HOSTS" | grep -o '{"id":[^}]*"domain_names":\["[^"]*explorer\.d-bis\.org[^"]*"[^}]*}' || echo "")

if [ -z "$EXPLORER_CONFIG" ]; then
    echo "❌ explorer.d-bis.org not found in NPMplus configuration"
    echo ""
    echo "Available domains:"
    echo "$PROXY_HOSTS" | grep -o '"domain_names":\["[^"]*"' | head -10
    exit 1
fi

echo "✅ Found explorer.d-bis.org configuration"
echo ""

# Extract configuration details
FORWARD_HOST=$(echo "$EXPLORER_CONFIG" | grep -o '"forward_host":"[^"]*' | cut -d'"' -f4 || echo "")
FORWARD_PORT=$(echo "$EXPLORER_CONFIG" | grep -o '"forward_port":[0-9]*' | cut -d':' -f2 || echo "")
FORWARD_SCHEME=$(echo "$EXPLORER_CONFIG" | grep -o '"forward_scheme":"[^"]*' | cut -d'"' -f4 || echo "")
SSL_ENABLED=$(echo "$EXPLORER_CONFIG" | grep -o '"ssl_forced":true' || echo "false")

echo "=== Configuration Details ==="
echo "Forward Host: $FORWARD_HOST"
echo "Forward Port: $FORWARD_PORT"
echo "Forward Scheme: $FORWARD_SCHEME"
echo "SSL Forced: $([ -n "$SSL_ENABLED" ] && echo "Yes" || echo "No")"
echo ""

# Check if configuration is correct
CORRECT=true
ISSUES=()

if [ "$FORWARD_HOST" != "192.168.11.140" ]; then
    CORRECT=false
    ISSUES+=("Forward host is $FORWARD_HOST, expected 192.168.11.140")
fi

if [ "$FORWARD_PORT" != "80" ]; then
    CORRECT=false
    ISSUES+=("Forward port is $FORWARD_PORT, expected 80")
fi

if [ "$FORWARD_SCHEME" != "http" ]; then
    CORRECT=false
    ISSUES+=("Forward scheme is $FORWARD_SCHEME, expected http")
fi

# Verify target is accessible
echo "=== Step 4: Verifying target accessibility ==="
TARGET_TEST=$(curl -s -o /dev/null -w '%{http_code}' --connect-timeout 5 "http://192.168.11.140:80/" 2>/dev/null || echo "000")
if [ "$TARGET_TEST" = "200" ]; then
    echo "✅ Target http://192.168.11.140:80 is accessible (HTTP $TARGET_TEST)"
else
    echo "⚠️  Target http://192.168.11.140:80 returned HTTP $TARGET_TEST"
    ISSUES+=("Target may not be accessible")
fi
echo ""

# Summary
echo "=========================================="
echo "Summary"
echo "=========================================="
if [ "$CORRECT" = true ]; then
    echo "✅ NPMplus is correctly configured for explorer.d-bis.org"
    echo ""
    echo "Configuration:"
    echo "  Domain: explorer.d-bis.org"
    echo "  Target: $FORWARD_SCHEME://$FORWARD_HOST:$FORWARD_PORT"
    echo "  VMID: 5000"
    echo "  Status: ✅ Correct"
else
    echo "❌ NPMplus configuration has issues:"
    echo ""
    for issue in "${ISSUES[@]}"; do
        echo "  - $issue"
    done
    echo ""
    echo "Expected configuration:"
    echo "  Domain: explorer.d-bis.org"
    echo "  Target: http://192.168.11.140:80"
    echo "  VMID: 5000"
    echo ""
    echo "Current configuration:"
    echo "  Target: $FORWARD_SCHEME://$FORWARD_HOST:$FORWARD_PORT"
fi
echo ""
