#!/bin/bash
# Configure NPMplus proxy host via API for cross-all.defi-oracle.io
# This script attempts to configure NPMplus via API if credentials are available

set -euo pipefail

# Try to load credentials from environment or common locations
if [ -f "$HOME/.env" ]; then
    export $(cat "$HOME/.env" | grep -v '^#' | xargs)
fi

if [ -f "/home/intlc/projects/proxmox/.env" ]; then
    export $(cat "/home/intlc/projects/proxmox/.env" | grep -v '^#' | xargs)
fi

# Default values (adjust if needed)
NPMPLUS_HOST="${1:-192.168.11.11}"
NPMPLUS_VMID="${2:-10233}"
NPM_URL="${NPM_URL:-https://192.168.11.166:81}"
NPM_EMAIL="${NPM_EMAIL:-nsatoshi2007@hotmail.com}"
NPM_PASSWORD="${NPM_PASSWORD:-}"

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 VIA API: $DOMAIN"
log_info "═══════════════════════════════════════════════════════════"
echo ""

# Step 1: Get NPMplus password if not provided
if [ -z "$NPM_PASSWORD" ]; then
    log_info "Step 1: Retrieving NPMplus admin password..."
    NPM_PASSWORD=$(ssh -o ConnectTimeout=10 root@"$NPMPLUS_HOST" \
        "pct exec $NPMPLUS_VMID -- cat /opt/.npm_pwd 2>/dev/null || docker exec npmplus cat /opt/.npm_pwd 2>/dev/null || echo ''" 2>/dev/null || echo "")
    
    if [ -z "$NPM_PASSWORD" ]; then
        log_error "Could not retrieve NPMplus password"
        log_info "Please provide NPM_PASSWORD as environment variable or configure manually via web interface"
        log_info "See NPMPLUS_CONFIGURATION.md for manual setup instructions"
        exit 1
    fi
    log_success "Password retrieved"
fi

# Step 2: Get NPMplus URL/IP
log_info "Step 2: Getting NPMplus IP address..."
NPMPLUS_IP=$(ssh -o ConnectTimeout=10 root@"$NPMPLUS_HOST" \
    "pct exec $NPMPLUS_VMID -- hostname -I | awk '{print \$1}'" 2>/dev/null || echo "")

if [ -n "$NPMPLUS_IP" ]; then
    NPM_URL="https://${NPMPLUS_IP}:81"
    log_success "NPMplus URL: $NPM_URL"
else
    log_warn "Could not determine NPMplus IP, using: $NPM_URL"
fi

# Step 3: Authenticate
log_info "Step 3: Authenticating to NPMplus API..."
TOKEN_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 "$TOKEN_RESPONSE" ]; then
    log_error "Failed to connect to NPMplus API at $NPM_URL"
    log_info "Please configure manually via web interface: $NPM_URL"
    exit 1
fi

TOKEN=$(echo "$TOKEN_RESPONSE" | jq -r '.token // empty' 2>/dev/null || echo "")

if [ -z "$TOKEN" ] || [ "$TOKEN" = "null" ]; then
    ERROR_MSG=$(echo "$TOKEN_RESPONSE" | jq -r '.error.message // "Unknown error"' 2>/dev/null || echo "$TOKEN_RESPONSE")
    log_error "Authentication failed: $ERROR_MSG"
    log_info "Please check credentials or configure manually via web interface"
    exit 1
fi

log_success "Authentication successful"

# Step 4: Check if proxy host already exists
log_info "Step 4: Checking for existing proxy host..."
EXISTING_HOSTS=$(curl -s -k -X GET "$NPM_URL/api/nginx/proxy-hosts" \
    -H "Authorization: Bearer $TOKEN" 2>/dev/null || echo "[]")

EXISTING_ID=$(echo "$EXISTING_HOSTS" | jq -r ".[] | select(.domain_names[] | contains(\"$DOMAIN\")) | .id" 2>/dev/null | head -1)

if [ -n "$EXISTING_ID" ] && [ "$EXISTING_ID" != "null" ]; then
    log_warn "Proxy host for $DOMAIN already exists (ID: $EXISTING_ID)"
    read -p "Update existing proxy host? (y/N): " -n 1 -r
    echo ""
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        log_info "Skipping update"
        exit 0
    fi
    UPDATE_EXISTING=true
else
    UPDATE_EXISTING=false
fi

# Step 5: Create/Update proxy host
log_info "Step 5: ${UPDATE_EXISTING:-false} && echo "Updating" || echo "Creating"} proxy host..."

PROXY_HOST_CONFIG=$(cat <<EOF
{
  "domain_names": ["$DOMAIN"],
  "forward_scheme": "http",
  "forward_host": "$BRIDGE_VM_IP",
  "forward_port": 80,
  "cache_assets": true,
  "block_exploits": true,
  "websockets_support": true,
  "access_list_id": "0",
  "advanced_config": "",
  "locations": []
}
EOF
)

if [ "$UPDATE_EXISTING" = true ]; then
    RESPONSE=$(curl -s -k -X PUT "$NPM_URL/api/nginx/proxy-hosts/$EXISTING_ID" \
        -H "Authorization: Bearer $TOKEN" \
        -H "Content-Type: application/json" \
        -d "$PROXY_HOST_CONFIG" 2>/dev/null || echo "")
else
    RESPONSE=$(curl -s -k -X POST "$NPM_URL/api/nginx/proxy-hosts" \
        -H "Authorization: Bearer $TOKEN" \
        -H "Content-Type: application/json" \
        -d "$PROXY_HOST_CONFIG" 2>/dev/null || echo "")
fi

PROXY_ID=$(echo "$RESPONSE" | jq -r '.id // empty' 2>/dev/null || echo "")

if [ -z "$PROXY_ID" ] || [ "$PROXY_ID" = "null" ]; then
    ERROR_MSG=$(echo "$RESPONSE" | jq -r '.error.message // "Unknown error"' 2>/dev/null || echo "$RESPONSE")
    log_error "Failed to ${UPDATE_EXISTING:-false} && echo "update" || echo "create"} proxy host: $ERROR_MSG"
    log_info "Please configure manually via web interface"
    exit 1
fi

log_success "Proxy host ${UPDATE_EXISTING:-false} && echo "updated" || echo "created"} (ID: $PROXY_ID)"

# Step 6: Request SSL certificate
log_info "Step 6: Requesting SSL certificate..."
SSL_CONFIG=$(cat <<EOF
{
  "force_ssl": true,
  "http2_support": true,
  "hsts_enabled": true,
  "hsts_subdomains": false,
  "certificate_id": 0
}
EOF
)

SSL_RESPONSE=$(curl -s -k -X POST "$NPM_URL/api/nginx/proxy-hosts/$PROXY_ID/ssl" \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d "$SSL_CONFIG" 2>/dev/null || echo "")

SSL_ERROR=$(echo "$SSL_RESPONSE" | jq -r '.error.message // empty' 2>/dev/null || echo "")

if [ -n "$SSL_ERROR" ] && [ "$SSL_ERROR" != "null" ]; then
    log_warn "SSL certificate request returned: $SSL_ERROR"
    log_info "You may need to request SSL certificate manually via web interface"
else
    log_success "SSL certificate configuration updated"
    log_info "Certificate issuance may take 1-2 minutes"
fi

# Step 7: Reload NPMplus
log_info "Step 7: Reloading NPMplus configuration..."
RELOAD_RESPONSE=$(curl -s -k -X POST "$NPM_URL/api/nginx/reload" \
    -H "Authorization: Bearer $TOKEN" 2>/dev/null || echo "")

log_success "NPMplus configuration reloaded"

# Step 8: Verify
log_info "Step 8: Verifying configuration..."
sleep 3

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 -k "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 (1-2 minutes)"
fi

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