#!/bin/bash

# Backup current config
cp /etc/apache2/sites-enabled/app2.syntheon.in.conf /var/www/html/livekit_frontend/app2.syntheon.in.conf.backup

# Update the config
cat > /etc/apache2/sites-enabled/app2.syntheon.in.conf << 'EOF'
<IfModule mod_ssl.c>
<VirtualHost *:443>
    ServerAdmin admin@mcube.com
    ServerName app2.syntheon.in
    ServerAlias app2.syntheon.in

    DocumentRoot /var/www/html

    # Proxy /livekit_frontend/ to Next.js app on port 3000 with /voicebot basePath
    <Location /livekit_frontend>
        ProxyPreserveHost On
        ProxyPass http://localhost:3000/voicebot
        ProxyPassReverse http://localhost:3000/voicebot
    </Location>

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

    # Default directory for other paths
    <Directory /var/www/html>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    <FilesMatch \.php$>
        SetHandler "proxy:unix:/run/php/php8.3-fpm.sock|fcgi://localhost/"
    </FilesMatch>

    ErrorLog ${APACHE_LOG_DIR}/app2.syntheon.in-error.log
    CustomLog ${APACHE_LOG_DIR}/app2.syntheon.in-access.log combined

    SSLEngine on
    Include /etc/letsencrypt/options-ssl-apache.conf
    SSLCertificateFile /etc/letsencrypt/live/app2.syntheon.in/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/app2.syntheon.in/privkey.pem
</VirtualHost>
</IfModule>
EOF

# Enable required Apache modules
a2enmod proxy proxy_http proxy_wstunnel rewrite headers

# Reload Apache
systemctl reload apache2

echo "Apache configuration updated successfully!"
echo "Access your app at: https://app2.syntheon.in/livekit_frontend/"
