#!/bin/bash

echo "==================================="
echo "LiveKit VoiceBot Deployment Script"
echo "==================================="
echo ""

# Colors for output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Configuration
DOMAIN="10.40.180.74"
FRONTEND_PORT=3000
BACKEND_DIR="/var/www/html/livekit_frontend/BackEnd/agent-starter-python"
FRONTEND_DIR="/var/www/html/livekit_frontend/FrontEnd/agent-starter-react/agent-starter-react"

echo "Step 1: Checking running processes..."
ps aux | grep -E "npm run start|uv run python" | grep -v grep

echo ""
echo "Step 2: Frontend and Backend are running:"
echo -e "${GREEN}✓${NC} Frontend: http://localhost:$FRONTEND_PORT"
echo -e "${GREEN}✓${NC} Backend: Python agent with uv"

echo ""
echo "Step 3: Apache Configuration"
echo "Creating Apache virtual host configuration..."

# Create Apache config
cat > /tmp/livekit-voicebot.conf << 'EOF'
<VirtualHost *:80>
    ServerName 10.40.180.74
    ServerAdmin admin@mcube.com

    # Frontend - Next.js production server on port 3000
    ProxyPreserveHost On
    ProxyPass / http://localhost:3000/
    ProxyPassReverse / http://localhost:3000/

    # WebSocket support for LiveKit
    RewriteEngine On
    RewriteCond %{HTTP:Upgrade} =websocket [NC]
    RewriteRule /(.*)           ws://localhost:3000/$1 [P,L]
    RewriteCond %{HTTP:Upgrade} !=websocket [NC]
    RewriteRule /(.*)           http://localhost:3000/$1 [P,L]

    # Logging
    ErrorLog ${APACHE_LOG_DIR}/livekit-voicebot-error.log
    CustomLog ${APACHE_LOG_DIR}/livekit-voicebot-access.log combined

    # Security headers
    Header always set X-Frame-Options "SAMEORIGIN"
    Header always set X-Content-Type-Options "nosniff"
    Header always set X-XSS-Protection "1; mode=block"

    # Allow larger uploads for audio/video
    LimitRequestBody 104857600

    # Timeout settings for long-running connections
    ProxyTimeout 300
    TimeOut 300
</VirtualHost>
EOF

echo ""
echo -e "${YELLOW}Manual steps required (run with sudo):${NC}"
echo "1. Copy Apache config:"
echo "   sudo cp /tmp/livekit-voicebot.conf /etc/apache2/sites-available/"
echo ""
echo "2. Enable the site:"
echo "   sudo a2ensite livekit-voicebot.conf"
echo ""
echo "3. Test Apache configuration:"
echo "   sudo apache2ctl configtest"
echo ""
echo "4. Reload Apache:"
echo "   sudo systemctl reload apache2"
echo ""
echo -e "${GREEN}After completing these steps, your application will be accessible at:${NC}"
echo "   http://10.40.180.74"
echo ""
echo "==================================="
echo "Current Service Status:"
echo "==================================="
netstat -tlnp 2>/dev/null | grep -E ':(80|3000)' || ss -tlnp | grep -E ':(80|3000)'
