#!/bin/bash

# Configure NPMplus proxy host for explorer.d-bis.org
# Uses NPMplus database directly to create/update configuration

set -uo pipefail

DOMAIN="explorer.d-bis.org"
NPMPLUS_VMID="10233"
NPMPLUS_NODE="r630-01"
VM_IP="192.168.11.140"
VM_PORT="80"

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

echo "=========================================="
echo "Configure NPMplus for explorer.d-bis.org"
echo "=========================================="
echo ""

# Check if proxy host exists
echo -e "${BLUE}=== Checking existing configuration ===${NC}"

EXISTING=$(ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
  "ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@$NPMPLUS_NODE 'pct exec $NPMPLUS_VMID -- docker exec npmplus node -e \"
const Database = require(\\\"better-sqlite3\\\");
const db = new Database(\\\"/data/npmplus/database.sqlite\\\");
const host = db.prepare(\\\"SELECT id, domain_names, forward_scheme, forward_host, forward_port, enabled FROM proxy_host WHERE domain_names LIKE \\\\\\\"%$DOMAIN%\\\\\\\"\\\").get();
console.log(JSON.stringify(host || {}));
db.close();
\" 2>&1'" 2>&1 || echo "{}")

if echo "$EXISTING" | jq -e '.id' >/dev/null 2>&1; then
    HOST_ID=$(echo "$EXISTING" | jq -r '.id')
    CURRENT_HOST=$(echo "$EXISTING" | jq -r '.forward_host // "unknown"')
    CURRENT_PORT=$(echo "$EXISTING" | jq -r '.forward_port // "unknown"')
    ENABLED=$(echo "$EXISTING" | jq -r '.enabled // false')
    
    echo -e "${GREEN}✅ Found existing proxy host (ID: $HOST_ID)${NC}"
    echo "   Current: $CURRENT_HOST:$CURRENT_PORT"
    echo "   Enabled: $ENABLED"
    
    # Update if needed
    if [ "$CURRENT_HOST" != "$VM_IP" ] || [ "$CURRENT_PORT" != "$VM_PORT" ] || [ "$ENABLED" != "true" ]; then
        echo -e "${YELLOW}⚠️  Updating configuration...${NC}"
        
        ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
          "ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@$NPMPLUS_NODE 'pct exec $NPMPLUS_VMID -- docker exec npmplus node -e \"
const Database = require(\\\"better-sqlite3\\\");
const db = new Database(\\\"/data/npmplus/database.sqlite\\\");
const stmt = db.prepare(\\\"UPDATE proxy_host SET forward_host = ?, forward_port = ?, forward_scheme = \\\\\\\"http\\\\\\\", enabled = 1 WHERE id = ?\\\");
stmt.run(\\\"$VM_IP\\\", $VM_PORT, $HOST_ID);
db.close();
console.log(\\\"Updated\\\");
\" 2>&1'" 2>&1
        
        echo -e "${GREEN}✅ Configuration updated${NC}"
    else
        echo -e "${GREEN}✅ Configuration is already correct${NC}"
    fi
else
    echo -e "${YELLOW}⚠️  Proxy host not found. Creating new one...${NC}"
    
    # Create new proxy host
    ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
      "ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@$NPMPLUS_NODE 'pct exec $NPMPLUS_VMID -- docker exec npmplus node -e \"
const Database = require(\\\"better-sqlite3\\\");
const db = new Database(\\\"/data/npmplus/database.sqlite\\\");

// Get next ID
const maxId = db.prepare(\\\"SELECT MAX(id) as max FROM proxy_host\\\").get();
const nextId = (maxId?.max || 0) + 1;

// Insert new proxy host
const stmt = db.prepare(\\\"INSERT INTO proxy_host (id, domain_names, forward_scheme, forward_host, forward_port, enabled, cache_assets, block_exploits, websockets_support, access_list_id, certificate_id, ssl_forced, hsts_enabled, hsts_subdomains, http2_support, advanced, locations, allow_websocket_upgrade, forward_http_headers, created_on, modified_on) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime(\\\"now\\\"), datetime(\\\"now\\\"))\\\");

stmt.run(
  nextId,
  JSON.stringify([\\\"$DOMAIN\\\"]),
  \\\"http\\\",
  \\\"$VM_IP\\\",
  $VM_PORT,
  1, // enabled
  1, // cache_assets
  1, // block_exploits
  0, // websockets_support
  0, // access_list_id
  0, // certificate_id
  0, // ssl_forced
  0, // hsts_enabled
  0, // hsts_subdomains
  0, // http2_support
  0, // advanced
  null, // locations
  0, // allow_websocket_upgrade
  0, // forward_http_headers
);

db.close();
console.log(\\\"Created\\\");
\" 2>&1'" 2>&1
    
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✅ Proxy host created${NC}"
    else
        echo -e "${RED}❌ Failed to create proxy host${NC}"
        echo "You may need to configure it via web UI: https://192.168.11.166:81"
        exit 1
    fi
fi

# Reload NPMplus
echo ""
echo -e "${BLUE}=== Reloading NPMplus ===${NC}"

ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
  "ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@$NPMPLUS_NODE 'pct exec $NPMPLUS_VMID -- docker exec npmplus nginx -s reload 2>&1'" 2>&1 || true

echo -e "${GREEN}✅ NPMplus reloaded${NC}"

# Verify
echo ""
echo -e "${BLUE}=== Verification ===${NC}"

sleep 2

# Test from NPMplus to target
NPMPLUS_TEST=$(ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
  "ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@$NPMPLUS_NODE 'pct exec $NPMPLUS_VMID -- curl -s -H \"Host: $DOMAIN\" -o /dev/null -w \"%{http_code}\" --connect-timeout 5 http://$VM_IP:80/ 2>/dev/null'" 2>&1 || echo "000")

if [ "$NPMPLUS_TEST" = "200" ]; then
    echo -e "${GREEN}✅ NPMplus can serve $DOMAIN (HTTP $NPMPLUS_TEST)${NC}"
else
    echo -e "${YELLOW}⚠️  NPMplus test returned HTTP $NPMPLUS_TEST${NC}"
fi

# Test external access
echo ""
echo "Testing external access..."
EXTERNAL_TEST=$(curl -s -o /dev/null -w '%{http_code}' --connect-timeout 5 --max-time 10 "https://$DOMAIN" 2>/dev/null || echo "000")

if [ "$EXTERNAL_TEST" = "200" ] || [ "$EXTERNAL_TEST" = "301" ] || [ "$EXTERNAL_TEST" = "302" ]; then
    echo -e "${GREEN}✅ External access working (HTTP $EXTERNAL_TEST)${NC}"
elif [ "$EXTERNAL_TEST" = "000" ]; then
    echo -e "${YELLOW}⚠️  External access timeout (may need UDM Pro port forwarding check)${NC}"
else
    echo -e "${YELLOW}⚠️  External access returned HTTP $EXTERNAL_TEST${NC}"
fi

echo ""
echo "=========================================="
echo "Configuration Complete"
echo "=========================================="
echo ""
