#!/bin/bash

echo "============================================"
echo "LiveKit VoiceBot - Complete Deployment"
echo "Domain: 10.40.180.74"
echo "============================================"
echo ""

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

# Step 1: Apache Configuration
echo -e "${YELLOW}Step 1: Configuring Apache...${NC}"
sudo cp /tmp/livekit-voicebot.conf /etc/apache2/sites-available/ 2>/dev/null || {
    echo "Creating Apache config..."
    cat > /tmp/livekit-voicebot.conf << 'EOF'
<VirtualHost *:80>
    ServerName 10.40.180.74
    ServerAdmin admin@mcube.com

    ProxyPreserveHost On
    ProxyPass / http://localhost:3000/
    ProxyPassReverse / http://localhost:3000/

    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]

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

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

    LimitRequestBody 104857600
    ProxyTimeout 300
    TimeOut 300
</VirtualHost>
EOF
    sudo cp /tmp/livekit-voicebot.conf /etc/apache2/sites-available/
}

# Step 2: Enable site
echo -e "${YELLOW}Step 2: Enabling site...${NC}"
sudo a2ensite livekit-voicebot.conf

# Step 3: Test configuration
echo -e "${YELLOW}Step 3: Testing Apache configuration...${NC}"
sudo apache2ctl configtest

# Step 4: Reload Apache
echo -e "${YELLOW}Step 4: Reloading Apache...${NC}"
sudo systemctl reload apache2

echo ""
echo -e "${GREEN}============================================${NC}"
echo -e "${GREEN}Deployment Complete!${NC}"
echo -e "${GREEN}============================================${NC}"
echo ""
echo "Your application is now accessible at:"
echo -e "${GREEN}http://10.40.180.74${NC}"
echo ""
echo "Services running:"
echo "  ✓ Frontend: http://localhost:3000 (proxied through Apache)"
echo "  ✓ Backend: Python agent with LiveKit"
echo ""
echo "To check logs:"
echo "  - Apache: sudo tail -f /var/log/apache2/livekit-voicebot-error.log"
echo "  - Frontend: tail -f /var/www/html/livekit_frontend/logs/frontend-out.log"
echo "  - Backend: tail -f /var/www/html/livekit_frontend/logs/backend-out.log"
echo ""
echo "============================================"
