#!/bin/bash

echo "=========================================="
echo "Fixing Apache Configuration for LiveKit"
echo "=========================================="
echo ""

# Backup current config
echo "1. Backing up current Apache config..."
sudo cp /etc/apache2/sites-enabled/app2.syntheon.in.conf /var/www/html/livekit_frontend/app2.syntheon.in.conf.backup
echo "   Backup saved to: /var/www/html/livekit_frontend/app2.syntheon.in.conf.backup"
echo ""

# Update the Apache config
echo "2. Applying new Apache configuration..."
sudo cp /var/www/html/livekit_frontend/app2-updated.conf /etc/apache2/sites-enabled/app2.syntheon.in.conf
echo "   Configuration updated"
echo ""

# Test configuration
echo "3. Testing Apache configuration..."
sudo apache2ctl configtest
CONFIG_TEST=$?

if [ $CONFIG_TEST -eq 0 ]; then
    echo "   ✓ Configuration test passed!"
    echo ""
    
    # Reload Apache
    echo "4. Reloading Apache..."
    sudo systemctl reload apache2
    echo "   ✓ Apache reloaded successfully!"
    echo ""
else
    echo "   ✗ Configuration test failed!"
    echo "   Please check the errors above."
    exit 1
fi

# Verify Next.js is running
echo "5. Verifying Next.js is running on port 3000..."
if ss -tlnp | grep -q :3000; then
    echo "   ✓ Next.js is running on port 3000"
else
    echo "   ✗ Next.js is NOT running on port 3000"
    echo "   Starting Next.js..."
    cd /var/www/html/livekit_frontend/FrontEnd/agent-starter-react/agent-starter-react
    nohup npm start > /tmp/nextjs.log 2>&1 &
    sleep 3
    if ss -tlnp | grep -q :3000; then
        echo "   ✓ Next.js started successfully"
    else
        echo "   ✗ Failed to start Next.js"
        exit 1
    fi
fi
echo ""

echo "=========================================="
echo "✓ Configuration Complete!"
echo "=========================================="
echo ""
echo "Your app is now accessible at:"
echo "  Frontend UI: https://app2.syntheon.in/voicebot"
echo "  API Routes:  https://app2.syntheon.in/voicebot/api/*"
echo ""
echo "Note: The /api path is part of the Next.js app at /voicebot/api/*"
echo ""
