#!/bin/bash

# Fix NPMplus for explorer.d-bis.org
# Starts NPMplus container and configures proxy host

set -uo pipefail

DOMAIN="explorer.d-bis.org"
NPMPLUS_VMID="10233"
NPMPLUS_NODE="r630-01"
NPMPLUS_IP="192.168.11.166"
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 "Fix NPMplus for explorer.d-bis.org"
echo "=========================================="
echo ""

# Step 1: Start NPMplus container
echo -e "${BLUE}=== Step 1: Starting NPMplus Container ===${NC}"

CONTAINER_STATUS=$(ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
  "ssh -o ConnectTimeout=5 root@$NPMPLUS_NODE 'pct status $NPMPLUS_VMID 2>/dev/null | awk \"{print \\\$2}\"'" 2>/dev/null || echo "unknown")

if [ "$CONTAINER_STATUS" = "running" ]; then
    echo -e "${GREEN}✅ NPMplus container is already running${NC}"
else
    echo "Starting NPMplus container..."
    ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
      "ssh -o ConnectTimeout=5 root@$NPMPLUS_NODE 'pct start $NPMPLUS_VMID'" 2>&1
    
    sleep 5
    
    CONTAINER_STATUS=$(ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
      "ssh -o ConnectTimeout=5 root@$NPMPLUS_NODE 'pct status $NPMPLUS_VMID 2>/dev/null | awk \"{print \\\$2}\"'" 2>/dev/null || echo "unknown")
    
    if [ "$CONTAINER_STATUS" = "running" ]; then
        echo -e "${GREEN}✅ NPMplus container started${NC}"
    else
        echo -e "${RED}❌ Failed to start NPMplus container${NC}"
        exit 1
    fi
fi

# Step 2: Wait for NPMplus to be ready
echo ""
echo -e "${BLUE}=== Step 2: Waiting for NPMplus to be ready ===${NC}"

for i in {1..30}; do
    if ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
      "ssh -o ConnectTimeout=5 root@$NPMPLUS_NODE 'pct exec $NPMPLUS_VMID -- curl -s http://localhost:81 >/dev/null 2>&1'" 2>/dev/null; then
        echo -e "${GREEN}✅ NPMplus is ready${NC}"
        break
    fi
    if [ $i -eq 30 ]; then
        echo -e "${YELLOW}⚠️  NPMplus may not be fully ready, continuing anyway...${NC}"
    else
        echo "Waiting for NPMplus... ($i/30)"
        sleep 2
    fi
done

# Step 3: Check if proxy host exists
echo ""
echo -e "${BLUE}=== Step 3: Checking NPMplus Configuration ===${NC}"

EXISTING_CONFIG=$(ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
  "ssh -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\\\", { readonly: true });
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>/dev/null || echo "{}")

if echo "$EXISTING_CONFIG" | jq -e '.id' >/dev/null 2>&1; then
    HOST_ID=$(echo "$EXISTING_CONFIG" | jq -r '.id')
    CURRENT_HOST=$(echo "$EXISTING_CONFIG" | jq -r '.forward_host // "unknown"')
    CURRENT_PORT=$(echo "$EXISTING_CONFIG" | jq -r '.forward_port // "unknown"')
    ENABLED=$(echo "$EXISTING_CONFIG" | jq -r '.enabled // false')
    
    echo "Found existing proxy host (ID: $HOST_ID)"
    echo "  Current target: $CURRENT_HOST:$CURRENT_PORT"
    echo "  Enabled: $ENABLED"
    
    if [ "$CURRENT_HOST" != "$VM_IP" ] || [ "$CURRENT_PORT" != "$VM_PORT" ]; then
        echo -e "${YELLOW}⚠️  Configuration mismatch. Updating...${NC}"
        
        # Update configuration
        ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
          "ssh -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>/dev/null
        
        echo -e "${GREEN}✅ Configuration updated${NC}"
    else
        echo -e "${GREEN}✅ Configuration is correct${NC}"
    fi
    
    if [ "$ENABLED" != "true" ]; then
        echo "Enabling proxy host..."
        ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
          "ssh -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 enabled = 1 WHERE id = ?\\\");
stmt.run($HOST_ID);
db.close();
console.log(\\\"Enabled\\\");
\" 2>&1'" 2>/dev/null
        
        echo -e "${GREEN}✅ Proxy host enabled${NC}"
    fi
else
    echo -e "${YELLOW}⚠️  Proxy host not found. Creating new one...${NC}"
    echo ""
    echo "To create the proxy host, you need to:"
    echo "  1. Access NPMplus web UI: https://$NPMPLUS_IP:81"
    echo "  2. Login with your credentials"
    echo "  3. Add Proxy Host:"
    echo "     - Domain Names: $DOMAIN"
    echo "     - Scheme: http"
    echo "     - Forward Hostname/IP: $VM_IP"
    echo "     - Forward Port: $VM_PORT"
    echo "     - Cache Assets: Yes"
    echo "     - Block Common Exploits: Yes"
    echo "     - Websockets Support: No"
    echo ""
    echo "Or use the NPMplus API to create it programmatically."
fi

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

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

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

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

sleep 2

# Test from NPMplus
NPMPLUS_TEST=$(ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
  "ssh -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>/dev/null || 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

echo ""
echo "=========================================="
echo "Fix Complete"
echo "=========================================="
echo ""
echo "Next steps:"
echo "  1. Verify NPMplus proxy host is configured"
echo "  2. Check UDM Pro port forwarding: $PUBLIC_IP:80/443 → $NPMPLUS_IP:80/443"
echo "  3. Test external access: curl -I https://$DOMAIN"
echo ""
