#!/bin/bash

# Ensure the script is run as root
if [ "$EUID" -ne 0 ]; then
    echo "Please run as root (e.g., sudo ./setup_apache_php.sh)"
    exit 1
fi

echo "Updating package list..."
sudo apt update

echo "Installing Apache..."
sudo apt install apache2 -y

echo "Starting and enabling Apache..."
sudo systemctl start apache2
sudo systemctl enable apache2

echo "Installing PHP and required modules..."
sudo apt install php libapache2-mod-php php-mysql php-cli php-curl php-gd php-xml php-mbstring -y

# Determine the PHP version (assume php8.2 as default if multiple exist)
PHP_VERSION=$(php -v | grep -oP '^PHP \K[0-9]+\.[0-9]+' || echo "8.2")
PHP_CONF_PATH="/etc/apache2/mods-enabled/php${PHP_VERSION}.conf"

# Check if the PHP config file exists
if [ ! -f "$PHP_CONF_PATH" ]; then
    echo "PHP configuration file not found at $PHP_CONF_PATH. Please verify the PHP version."
    exit 1
fi

echo "Modifying PHP configuration file to allow PHP in .html files..."

# Add the FilesMatch directive for .html files
sudo sed -i '/<\/IfModule>/i <FilesMatch "\\.(php|html)$">\n    SetHandler application/x-httpd-php\n</FilesMatch>' "$PHP_CONF_PATH"

echo "Restarting Apache to apply changes..."
sudo systemctl restart apache2

echo "Creating a test .html file to verify PHP processing..."
TEST_FILE="/var/www/html/test.html"

cat <<EOF | sudo tee $TEST_FILE
<html>
    <head><title>PHP Test</title></head>
    <body>
        <h1>Testing PHP in HTML</h1>
        <p>Server Time: <?php echo date("Y-m-d H:i:s"); ?></p>
    </body>
</html>
EOF

echo "Test file created: $TEST_FILE"

echo "Allowing HTTP and HTTPS traffic through the firewall..."
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw allo ssh
sudo ufw enable

echo "You can test the PHP setup by visiting: http://<your-server-ip>/test.html"

echo "Installation and setup of Apache and PHP are complete!"
