#!/usr/bin/env bash
# Set up /beta/ path for SolaceScanScout testing
# Usage: ./setup-beta-path.sh

set -euo pipefail

IP="${IP:-192.168.11.140}"
DOMAIN="${DOMAIN:-explorer.d-bis.org}"
PASSWORD="${PASSWORD:-L@kers2010}"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
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"; }
log_step() { echo -e "${CYAN}[STEP]${NC} $1"; }

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
FRONTEND_FILE="$PROJECT_ROOT/explorer-monorepo/frontend/public/index.html"

if [ ! -f "$FRONTEND_FILE" ]; then
    log_error "Frontend file not found: $FRONTEND_FILE"
    exit 1
fi

echo "════════════════════════════════════════════════════════"
echo "Set up Beta Path for SolaceScanScout"
echo "════════════════════════════════════════════════════════"
echo ""

log_step "Step 1: Creating beta directory..."
sshpass -p "$PASSWORD" ssh -o StrictHostKeyChecking=no root@"$IP" \
    "mkdir -p /var/www/html/beta && chmod 755 /var/www/html/beta"

log_success "Beta directory created"

log_step "Step 2: Deploying SolaceScanScout to beta path..."
sshpass -p "$PASSWORD" scp -o StrictHostKeyChecking=no \
    "$FRONTEND_FILE" \
    root@"$IP":/var/www/html/beta/index.html

log_success "Files deployed to /beta/"

log_step "Step 3: Configuring nginx for /beta/ path..."
sshpass -p "$PASSWORD" ssh -o StrictHostKeyChecking=no root@"$IP" << 'NGINX_CONFIG'
# Check if nginx config exists
NGINX_CONF="/etc/nginx/sites-available/explorer"
if [ ! -f "$NGINX_CONF" ]; then
    # Find the actual nginx config file
    NGINX_CONF=$(ls /etc/nginx/sites-enabled/* 2>/dev/null | head -1)
    if [ -z "$NGINX_CONF" ]; then
        NGINX_CONF="/etc/nginx/sites-available/default"
    fi
fi

# Backup config
cp "$NGINX_CONF" "${NGINX_CONF}.backup.$(date +%Y%m%d_%H%M%S)"

# Check if beta location already exists
if grep -q "location /beta" "$NGINX_CONF"; then
    echo "Beta location already exists, updating..."
    # Remove existing beta location block
    sed -i '/location \/beta/,/^[[:space:]]*}/d' "$NGINX_CONF"
fi

# Add beta location block before the main location block
# Find the main location / block and insert before it
if grep -q "location / {" "$NGINX_CONF"; then
    # Insert beta location before main location
    sed -i '/location \/ {/i\
    # Beta path for SolaceScanScout testing\
    location /beta {\
        alias /var/www/html/beta;\
        index index.html;\
        try_files $uri $uri/ /beta/index.html;\
    }\
' "$NGINX_CONF"
else
    # Append to end of server block
    sed -i '/server {/a\
    # Beta path for SolaceScanScout testing\
    location /beta {\
        alias /var/www/html/beta;\
        index index.html;\
        try_files $uri $uri/ /beta/index.html;\
    }\
' "$NGINX_CONF"
fi

# Test nginx configuration
if nginx -t 2>/dev/null; then
    echo "Nginx configuration is valid"
    systemctl reload nginx
    echo "Nginx reloaded successfully"
else
    echo "ERROR: Nginx configuration test failed"
    echo "Restoring backup..."
    cp "${NGINX_CONF}.backup."* "$NGINX_CONF" 2>/dev/null || true
    exit 1
fi
NGINX_CONFIG

if [ $? -eq 0 ]; then
    log_success "Nginx configured for /beta/ path"
else
    log_error "Failed to configure nginx"
    exit 1
fi

log_step "Step 4: Verifying beta path..."
sleep 2
if curl -k -sI "https://$DOMAIN/beta/" 2>&1 | grep -qi "HTTP.*200"; then
    log_success "Beta path is accessible!"
    
    # Check if it shows SolaceScanScout
    if curl -k -s "https://$DOMAIN/beta/" 2>&1 | grep -qi "SolaceScanScout"; then
        log_success "SolaceScanScout is live at beta path!"
    else
        log_warn "Beta path accessible but may not show SolaceScanScout - check manually"
    fi
else
    log_warn "Beta path may not be accessible - check nginx configuration"
fi

echo ""
log_success "════════════════════════════════════════════════════════"
log_success "Beta Path Setup Complete!"
log_success "════════════════════════════════════════════════════════"
echo ""
log_info "Beta URL: https://$DOMAIN/beta/"
log_info "Production URL: https://$DOMAIN/ (unchanged)"
echo ""
log_info "To test:"
log_info "  curl -k https://$DOMAIN/beta/"
log_info "  or visit: https://$DOMAIN/beta/ in your browser"
echo ""

