#!/bin/bash
# Fix ProxyPassMatch configuration for puebloarabesque.scala4.com

echo "=== Fixing puebloarabesque.scala4.com configuration ==="
echo ""

# Files to fix
SSL_FILE="/etc/apache2/sites-available/010-puebloarabesque-le-ssl.conf"
HTTP_FILE="/etc/apache2/sites-available/010-puebloarabesque.conf"

# Backup files
echo "1. Creating backups..."
sudo cp "$SSL_FILE" "${SSL_FILE}.backup-$(date +%Y%m%d-%H%M%S)"
sudo cp "$HTTP_FILE" "${HTTP_FILE}.backup-$(date +%Y%m%d-%H%M%S)"
echo "   ✓ Backups created"

# Fix HTTPS configuration
echo ""
echo "2. Fixing HTTPS configuration..."
# Replace the ProxyPassMatch line to include document root path
sudo sed -i 's|fcgi://localhost/"|fcgi://localhost/var/www/html/puebloarabesque/$1"|' "$SSL_FILE"
echo "   ✓ HTTPS config updated"

# Fix HTTP configuration
echo ""
echo "3. Fixing HTTP configuration..."
# Replace the ProxyPassMatch line to include document root path
sudo sed -i 's|fcgi://localhost/"|fcgi://localhost/var/www/html/puebloarabesque/$1"|' "$HTTP_FILE"
echo "   ✓ HTTP config updated"

# Verify the fix
echo ""
echo "4. Verifying configuration..."
if grep -q "fcgi://localhost/var/www/html/puebloarabesque/\$1" "$SSL_FILE"; then
    echo "   ✓ HTTPS config verified"
else
    echo "   ⚠️  HTTPS config may not be correct"
fi

if grep -q "fcgi://localhost/var/www/html/puebloarabesque/\$1" "$HTTP_FILE"; then
    echo "   ✓ HTTP config verified"
else
    echo "   ⚠️  HTTP config may not be correct"
fi

# Test Apache configuration
echo ""
echo "5. Testing Apache configuration..."
if sudo apache2ctl configtest; then
    echo "   ✓ Configuration is valid"
    
    # Reload Apache
    echo ""
    echo "6. Reloading Apache..."
    if sudo systemctl reload apache2; then
        echo "   ✓ Apache reloaded"
        
        # Wait a moment for Apache to reload
        sleep 2
        
        # Test the site
        echo ""
        echo "7. Testing site..."
        HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" https://puebloarabesque.scala4.com/)
        echo "   HTTP Status: $HTTP_CODE"
        
        if [ "$HTTP_CODE" = "200" ] || [ "$HTTP_CODE" = "301" ] || [ "$HTTP_CODE" = "302" ]; then
            echo ""
            echo "✅ SUCCESS! Site is working!"
            echo ""
            echo "Access at: https://puebloarabesque.scala4.com/"
        else
            echo ""
            echo "⚠️  Still getting $HTTP_CODE"
            echo ""
            echo "Please check:"
            echo "  - sudo tail -20 /var/log/apache2/error.log"
            echo "  - sudo tail -20 /var/log/php7.4-fpm.log"
        fi
    else
        echo "   ❌ Failed to reload Apache"
    fi
else
    echo "   ❌ Configuration has errors"
    exit 1
fi

echo ""
echo "Done!"

