#!/bin/bash

# Script to update PHP upload limits for all PHP versions and configurations
# Usage: sudo bash fix-php-upload-limits.sh

echo "=== Fixing PHP Upload Limits ==="

# Find all php.ini files
PHP_INI_FILES=$(find /etc/php -name "php.ini" 2>/dev/null)

if [ -z "$PHP_INI_FILES" ]; then
    echo "No php.ini files found in /etc/php"
    exit 1
fi

for ini_file in $PHP_INI_FILES; do
    echo ""
    echo "Processing: $ini_file"
    
    # Backup original file
    if [ ! -f "${ini_file}.backup" ]; then
        cp "$ini_file" "${ini_file}.backup"
        echo "  - Created backup: ${ini_file}.backup"
    fi
    
    # Update upload_max_filesize
    if grep -q "^upload_max_filesize" "$ini_file"; then
        sed -i 's/^upload_max_filesize = .*/upload_max_filesize = 128M/' "$ini_file"
        echo "  - Updated upload_max_filesize = 128M"
    else
        echo "upload_max_filesize = 128M" >> "$ini_file"
        echo "  - Added upload_max_filesize = 128M"
    fi
    
    # Update post_max_size
    if grep -q "^post_max_size" "$ini_file"; then
        sed -i 's/^post_max_size = .*/post_max_size = 130M/' "$ini_file"
        echo "  - Updated post_max_size = 130M"
    else
        echo "post_max_size = 130M" >> "$ini_file"
        echo "  - Added post_max_size = 130M"
    fi
    
    # Verify changes
    echo "  - Current values:"
    grep -E "^(upload_max_filesize|post_max_size)" "$ini_file" | sed 's/^/    /'
done

echo ""
echo "=== Restarting Services ==="

# Restart PHP-FPM if running
if systemctl is-active --quiet php8.2-fpm 2>/dev/null; then
    systemctl restart php8.2-fpm
    echo "- Restarted php8.2-fpm"
elif systemctl is-active --quiet php8.1-fpm 2>/dev/null; then
    systemctl restart php8.1-fpm
    echo "- Restarted php8.1-fpm"
elif systemctl is-active --quiet php8.0-fpm 2>/dev/null; then
    systemctl restart php8.0-fpm
    echo "- Restarted php8.0-fpm"
fi

# Restart Apache if running
if systemctl is-active --quiet apache2 2>/dev/null; then
    systemctl restart apache2
    echo "- Restarted apache2"
fi

# Restart Nginx if running
if systemctl is-active --quiet nginx 2>/dev/null; then
    systemctl restart nginx
    echo "- Restarted nginx"
fi

echo ""
echo "=== Done! ==="
echo "PHP upload limits have been updated to:"
echo "  - upload_max_filesize = 128M"
echo "  - post_max_size = 130M"
