#!/bin/bash

MAX_UPLOAD_SIZE=${1:-"100M"} # Default to 100M if not specified

# Nginx and Apache configuration paths (change these paths as necessary)
NGINX_CONF_PATH="/etc/nginx/nginx.conf"
APACHE_CONF_PATH="/etc/apache2/apache2.conf"
APACHE_VHOST_PATH="/etc/apache2/sites-available/000-default.conf" # Update to your specific virtual host file if different

# Function to get the installed PHP version
get_php_version() {
    php_version=$(php -v | grep -oP '^PHP \K[0-9]+\.[0-9]+' | head -1)
    if [ -z "$php_version" ]; then
        php_version="8.3"
    fi
    echo $php_version
}

# Function to update PHP configuration
update_php() {
  echo "Updating PHP configuration..."
  sudo cp $PHP_INI_PATH "${PHP_INI_PATH}.bak"
  sudo sed -i "s/upload_max_filesize = .*/upload_max_filesize = $MAX_UPLOAD_SIZE/" $PHP_INI_PATH
  sudo sed -i "s/post_max_size = .*/post_max_size = $MAX_UPLOAD_SIZE/" $PHP_INI_PATH
}

# Function to update Nginx configuration
update_nginx() {
    echo "Updating Nginx configuration..."
    if ! grep -q "client_max_body_size" $NGINX_CONF_PATH; then
        sudo sed -i "/http {/a \\\tclient_max_body_size $MAX_UPLOAD_SIZE;" $NGINX_CONF_PATH
    else
        sudo sed -i "s/client_max_body_size .*/client_max_body_size $MAX_UPLOAD_SIZE;/" $NGINX_CONF_PATH
    fi
    sudo systemctl restart nginx
}

# Function to update Apache configuration
update_apache() {
    echo "Updating Apache configuration..."
    # Ensure php_value directives are allowed with AllowOverride All or by direct insertion
    if grep -q "AllowOverride All" $APACHE_CONF_PATH || grep -q "AllowOverride All" $APACHE_VHOST_PATH; then
        echo "AllowOverride All found. Attempting to update .htaccess..."
        echo "php_value upload_max_filesize $MAX_UPLOAD_SIZE" >> /var/www/html/.htaccess
        echo "php_value post_max_size $MAX_UPLOAD_SIZE" >> /var/www/html/.htaccess
    else
        echo "Adding php_value directives directly to $APACHE_VHOST_PATH"
        sudo sed -i "/<\/VirtualHost>/i \\\tphp_value upload_max_filesize $MAX_UPLOAD_SIZE\n\tphp_value post_max_size $MAX_UPLOAD_SIZE" $APACHE_VHOST_PATH
    fi
    sudo systemctl restart apache2
}

# Get the installed PHP version
PHP_VERSION=$(get_php_version)

# Check and update Nginx configuration if exists
if [ -f "$NGINX_CONF_PATH" ]; then
    PHP_INI_PATH=${2:-"/etc/php/$PHP_VERSION/fpm/php.ini"}
    update_nginx
fi

# Check and update Apache configuration if exists
if [ -f "$APACHE_CONF_PATH" ]; then
    PHP_INI_PATH=${2:-"/etc/php/$PHP_VERSION/apache2/php.ini"}
    update_apache
fi

# Update PHP configuration
update_php

echo "Configuration update complete."