#!/bin/bash

# Configure Let's Encrypt SSL Certificate for explorer.d-bis.org in NPMplus
# Uses database directly (bypasses API if needed)

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
ROOT_ENV="$(cd "$PROJECT_ROOT/.." && pwd)/.env"

# Source .env files
if [ -f "$ROOT_ENV" ]; then
    set +euo pipefail
    source "$ROOT_ENV" 2>/dev/null || true
    set -euo pipefail
fi

# NPMplus configuration
NPMPLUS_VMID="10233"
NPMPLUS_NODE="r630-01"
DOMAIN="explorer.d-bis.org"
EMAIL="${NPM_EMAIL:-nsatoshi2007@hotmail.com}"

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

echo "=========================================="
echo "Configure Let's Encrypt Certificate (DB)"
echo "=========================================="
echo ""
echo "Domain: $DOMAIN"
echo "Email: $EMAIL"
echo ""

# Step 1: Check if proxy host exists
echo -e "${BLUE}Step 1: Checking proxy host in database...${NC}"
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/npm/database.sqlite\\\"); \
      const host = db.prepare(\\\"SELECT id, domain_names, forward_host, forward_port, ssl_certificate_id FROM proxy_host WHERE domain_names LIKE \\\\\\\"%${DOMAIN}%\\\\\\\"\\\").get(); \
      console.log(JSON.stringify(host || {})); \
      db.close();\" 2>&1'" 2>&1)

if echo "$PROXY_HOST" | jq -e '.id' >/dev/null 2>&1; then
    PROXY_HOST_ID=$(echo "$PROXY_HOST" | jq -r '.id')
    echo -e "${GREEN}✅ Found proxy host ID: $PROXY_HOST_ID${NC}"
    echo "  Domain: $(echo "$PROXY_HOST" | jq -r '.domain_names')"
    echo "  Forward: $(echo "$PROXY_HOST" | jq -r '.forward_host'):$(echo "$PROXY_HOST" | jq -r '.forward_port')"
else
    echo -e "${RED}❌ Proxy host for $DOMAIN not found${NC}"
    exit 1
fi

# Step 2: Check for existing certificate
echo -e "${BLUE}Step 2: Checking for existing certificate...${NC}"
EXISTING_CERT=$(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/npm/database.sqlite\\\"); \
      const cert = db.prepare(\\\"SELECT id, friendly_name, provider FROM ssl_certificate WHERE friendly_name = \\\\\\\"${DOMAIN}\\\\\\\" OR domains LIKE \\\\\\\"%${DOMAIN}%\\\\\\\"\\\").get(); \
      console.log(JSON.stringify(cert || {})); \
      db.close();\" 2>&1'" 2>&1)

if echo "$EXISTING_CERT" | jq -e '.id' >/dev/null 2>&1; then
    CERT_ID=$(echo "$EXISTING_CERT" | jq -r '.id')
    echo -e "${YELLOW}⚠️  Certificate already exists (ID: $CERT_ID)${NC}"
    echo "Using existing certificate..."
else
    echo -e "${YELLOW}⚠️  No existing certificate found${NC}"
    echo ""
    echo "To create a Let's Encrypt certificate:"
    echo "1. Access NPMplus dashboard: https://192.168.11.167:81"
    echo "2. Go to SSL Certificates → Add SSL Certificate"
    echo "3. Select Let's Encrypt"
    echo "4. Domain: $DOMAIN"
    echo "5. Email: $EMAIL"
    echo "6. Save and wait 1-2 minutes"
    echo ""
    echo "Or use the API-based script after certificate is created."
    exit 0
fi

# Step 3: Assign certificate to proxy host
echo -e "${BLUE}Step 3: Assigning certificate to proxy host...${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/npm/database.sqlite\\\"); \
      db.prepare(\\\"UPDATE proxy_host SET ssl_certificate_id = ?, ssl_forced = 1, http2_support = 1, hsts_enabled = 1 WHERE id = ?\\\").run(${CERT_ID}, ${PROXY_HOST_ID}); \
      console.log(\\\"Updated proxy host ${PROXY_HOST_ID} with certificate ${CERT_ID}\\\"); \
      db.close();\" 2>&1'" 2>&1

echo -e "${GREEN}✅ Certificate assigned to proxy host${NC}"
echo ""
echo "=========================================="
echo "Configuration Complete!"
echo "=========================================="
echo ""
echo "Summary:"
echo "  - Domain: $DOMAIN"
echo "  - Certificate ID: $CERT_ID"
echo "  - Proxy Host ID: $PROXY_HOST_ID"
echo "  - SSL Forced: Enabled"
echo "  - HTTP/2: Enabled"
echo "  - HSTS: Enabled"
echo ""
echo "Note: NPMplus will reload nginx automatically"
echo "Wait 10-30 seconds, then test:"
echo "  curl -I https://$DOMAIN"
echo ""
