#!/usr/bin/env bash

set -e

# --- Configuration Variables ---
DOMAIN="trublu.trubluhq.com"
APP_DIR="/var/www/trublu"
APACHE_CONF="/etc/apache2/sites-available/trublu.conf"
APACHE_SSL_CONF="/etc/apache2/sites-available/trublu-ssl.conf"

echo "=========================================================="
echo " Running Trublu Maintenance & Deployment Routine"
echo "=========================================================="

# 1. Update HTTP VirtualHost (Port 80)
echo "[1/5] Syncing HTTP VirtualHost..."
cat <<EOF > "${APACHE_CONF}"
<VirtualHost *:80>
    ServerName ${DOMAIN}
    ServerAlias www.${DOMAIN}
    DocumentRoot ${APP_DIR}/public

    <Directory ${APP_DIR}/public>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    <Directory ${APP_DIR}/public/.well-known>
        AllowOverride None
        Require all granted
    </Directory>

    ErrorLog \${APACHE_LOG_DIR}/trublu_error.log
    CustomLog \${APACHE_LOG_DIR}/trublu_access.log combined
</VirtualHost>
EOF

# 2. Update HTTPS VirtualHost (Port 443) with Path Fixes & Reverb Proxy
echo "[2/5] Syncing HTTPS VirtualHost with Aliases..."
cat <<EOF > "${APACHE_SSL_CONF}"
<IfModule mod_ssl.c>
<VirtualHost *:443>
    ServerName ${DOMAIN}
    ServerAlias www.${DOMAIN}
    DocumentRoot ${APP_DIR}/public

    RewriteEngine On
    SSLEngine on
    SSLCertificateFile    /etc/letsencrypt/live/${DOMAIN}/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/${DOMAIN}/privkey.pem

    # Trust Cloudflare / WireGuard proxy protocol
    SetEnvIf X-Forwarded-Proto "^https$" HTTPS=on

    # CGI device uuid support
    ScriptAlias /api/device/uuid ${APP_DIR}/device-uuid.sh
    <Directory ${APP_DIR}>
        Options +ExecCGI
        AddHandler cgi-script .sh
        Require all granted
    </Directory>

    # Blade template asset fixes
    Alias /storage/app/public ${APP_DIR}/storage/app/public
    Alias /storage/app/media  ${APP_DIR}/storage/app/media
    Alias /resources/themes   ${APP_DIR}/resources/themes
    Alias /public             ${APP_DIR}/public

    <Directory ${APP_DIR}/public>
        Options -Indexes +FollowSymLinks +ExecCGI
        AllowOverride All
        Require all granted
    </Directory>

    <Directory ${APP_DIR}/storage/app/public>
        Options -Indexes +FollowSymLinks
        AllowOverride None
        Require all granted
    </Directory>

    <Directory ${APP_DIR}/storage/app/media>
        Options -Indexes +FollowSymLinks
        AllowOverride None
        Require all granted
    </Directory>

    <Directory ${APP_DIR}/resources/themes>
        Options -Indexes +FollowSymLinks
        AllowOverride None
        Require all granted
    </Directory>

    # Laravel Reverb WebSocket proxy
    ProxyPreserveHost On
    ProxyRequests Off

    RewriteCond %{HTTP:Upgrade} =websocket [NC]
    RewriteRule ^/app/(.*) ws://127.0.0.1:8081/app/\$1 [P,L]

    RewriteCond %{HTTP:Upgrade} !=websocket [NC]
    RewriteRule ^/app/(.*) http://127.0.0.1:8081/app/\$1 [P,L]

    ProxyPass /app http://127.0.0.1:8081/app
    ProxyPassReverse /app http://127.0.0.1:8081/app

    ErrorLog \${APACHE_LOG_DIR}/trublu-ssl-error.log
    CustomLog \${APACHE_LOG_DIR}/trublu-ssl-access.log combined
</VirtualHost>
</IfModule>
EOF

# 3. Refresh Storage Symlink
echo "[3/5] Re-verifying storage symlink..."
cd "${APP_DIR}"
if [ -L "${APP_DIR}/public/storage" ]; then
    rm "${APP_DIR}/public/storage"
fi
php artisan storage:link --quiet || true

# 4. Enforce Permissions
echo "[4/5] Setting folder permissions and ownership..."
chown -R www-data:www-data "${APP_DIR}/storage" "${APP_DIR}/bootstrap/cache" "${APP_DIR}/resources/themes" "${APP_DIR}/public"
chmod -R 775 "${APP_DIR}/storage" "${APP_DIR}/bootstrap/cache"
find "${APP_DIR}/public" -type d -exec chmod 755 {} \;
find "${APP_DIR}/public" -type f -exec chmod 644 {} \;

# Clear and rebuild framework cache
php artisan optimize:clear

# 5. Reload Services
echo "[5/5] Reloading Apache..."
apache2ctl configtest
systemctl reload apache2

echo "=========================================================="
echo " Routine complete! ${DOMAIN} is up to date."
echo "=========================================================="
