#!/bin/bash
# Add ProxyPassMatch configuration for billing site (PHP 7.4)
# Run with: sudo bash add-billing-proxypassmatch.sh

echo "=== Adding ProxyPassMatch for Billing Site (PHP 7.4) ==="
echo ""

SSL_FILE="/etc/apache2/sites-available/004-billing-le-ssl.conf"
HTTP_FILE="/etc/apache2/sites-available/004-billing.conf"

# Check if ProxyPassMatch already exists
if grep -q "ProxyPassMatch.*php" "$SSL_FILE"; then
    echo "⚠️  ProxyPassMatch already exists. Updating..."
    # Update existing line
    sudo sed -i 's|ProxyPassMatch.*php.*|ProxyPassMatch "^/(.*\.php(/.*)?)$" "unix:/run/php/php7.4-scala4.sock|fcgi://localhost/var/www/html/billing/$1"|' "$SSL_FILE"
    sudo sed -i 's|ProxyPassMatch.*php.*|ProxyPassMatch "^/(.*\.php(/.*)?)$" "unix:/run/php/php7.4-scala4.sock|fcgi://localhost/var/www/html/billing/$1"|' "$HTTP_FILE"
else
    echo "Adding ProxyPassMatch after DocumentRoot..."
    # Add after DocumentRoot line
    sudo sed -i '/^[[:space:]]*DocumentRoot \/var\/www\/html\/billing/a\
\
	# Exclude phpmyadmin from ProxyPassMatch FIRST\
	ProxyPassMatch "^/phpmyadmin" "!"\
\
	# PHP 7.4 - user scala4\
	ProxyPassMatch "^/(.*\.php(/.*)?)$" "unix:/run/php/php7.4-scala4.sock|fcgi://localhost/var/www/html/billing/$1"
' "$SSL_FILE"
    
    sudo sed -i '/^[[:space:]]*DocumentRoot \/var\/www\/html\/billing/a\
\
	# Exclude phpmyadmin from ProxyPassMatch FIRST\
	ProxyPassMatch "^/phpmyadmin" "!"\
\
	# PHP 7.4 - user scala4\
	ProxyPassMatch "^/(.*\.php(/.*)?)$" "unix:/run/php/php7.4-scala4.sock|fcgi://localhost/var/www/html/billing/$1"
' "$HTTP_FILE"
fi

echo "✓ Configuration added"
echo ""

echo "Verifying configuration:"
grep -A 2 "DocumentRoot.*billing" "$SSL_FILE" | head -5
echo ""

echo "Testing Apache configuration..."
sudo apache2ctl configtest

if [ $? -eq 0 ]; then
    echo "✓ Configuration valid!"
    echo ""
    echo "Reloading Apache..."
    sudo systemctl reload apache2
    sleep 2
    echo "✓ Apache reloaded"
    echo ""
    echo "Testing billing site..."
    sleep 2
    HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" https://billing.friendlytv.site/ 2>&1)
    echo "   HTTP Status: $HTTP_CODE"
    
    if [ "$HTTP_CODE" = "200" ]; then
        echo ""
        echo "✅ SUCCESS! Billing site is working with PHP 7.4!"
    else
        echo ""
        echo "⚠️  Still getting $HTTP_CODE"
        echo "   Check: sudo tail -10 /var/log/apache2/error.log"
    fi
else
    echo "❌ Configuration error"
    exit 1
fi

