#!/bin/bash

# Bash script to set up a LAMP stack on Ubuntu with UFW configuration

# Define variables
domain_name="your_domain"
site_dir="/var/www/$domain_name"
php_test_file="$site_dir/info.php"

# Update and upgrade packages
echo "Updating package lists..."
sudo apt update && sudo apt upgrade -y

# Install and configure UFW
echo "Installing and setting up UFW (Uncomplicated Firewall)..."
sudo apt install ufw -y
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow OpenSSH
sudo ufw allow "Apache Full"
sudo ufw enable

# Verify UFW status
echo "Firewall setup completed! UFW status:"
sudo ufw status

# Install Apache
echo "Installing Apache..."
sudo apt install apache2 -y

# Check Apache status
echo "Verifying Apache installation..."
if systemctl is-active --quiet apache2; then
  echo "Apache is running!"
else
  echo "Error: Apache installation failed."
  exit 1
fi

# Install MySQL
echo "Installing MySQL..."
sudo apt install mysql-server -y

# Secure MySQL installation
echo "Securing MySQL installation..."
sudo mysql_secure_installation <<EOF

y
n
y
y
y
EOF

# Install PHP
echo "Installing PHP and required modules..."
sudo apt install php libapache2-mod-php php-mysql -y

# Verify PHP installation
echo "Checking PHP version..."
php -v

# Create directory for the website
echo "Creating directory for the website..."
sudo mkdir -p $site_dir
sudo chown -R $USER:$USER $site_dir
echo "<html><body><h1>Welcome to $domain_name!</h1></body></html>" > $site_dir/index.html

# Configure Apache virtual host
echo "Setting up Apache virtual host for $domain_name..."
sudo cat <<EOL | sudo tee /etc/apache2/sites-available/$domain_name.conf
<VirtualHost *:80>
    ServerName $domain_name
    ServerAlias www.$domain_name
    DocumentRoot $site_dir
    <Directory $site_dir>
        AllowOverride All
        Require all granted
    </Directory>
    ErrorLog \${APACHE_LOG_DIR}/$domain_name-error.log
    CustomLog \${APACHE_LOG_DIR}/$domain_name-access.log combined
</VirtualHost>
EOL

# Enable the new virtual host and reload Apache
echo "Enabling virtual host and reloading Apache..."
sudo a2ensite $domain_name
sudo systemctl reload apache2

# Create a PHP info file
echo "Creating a PHP info file..."
echo "<?php phpinfo(); ?>" > $php_test_file

# Output success message
echo "LAMP stack installation completed!"
echo "Firewall is active, and Apache is configured."
echo "To verify PHP, visit: http://$domain_name/info.php"
