#!/bin/bash -x

# Load env variables
source .env

# Get the script's directory
SCRIPT_PATH=$(dirname "$(realpath "${BASH_SOURCE[0]}")")

# Enable nginx to start with system
sudo systemctl enable --now nginx

# Setup nginx
sudo rm /etc/nginx/sites-enabled/default
sudo ln -fs $SCRIPT_PATH/nginx/wordpress /etc/nginx/sites-available
sudo ln -fs /etc/nginx/sites-available/wordpress /etc/nginx/sites-enabled/wordpress
sudo ln -fs $SCRIPT_PATH/phpmyadmin/phpmyadmin /etc/nginx/sites-available
sudo ln -fs /etc/nginx/sites-available/phpmyadmin /etc/nginx/sites-enabled/phpmyadmin

# Check for error
sudo nginx -t

# Restart nginx after loading wordpress config
sudo systemctl restart nginx
sudo systemctl status nginx

# PHP
sudo systemctl enable --now php8.4-fpm

# Set limit to post size and upload file size
sudo sed -i "s/^post_max_size = 8M/post_max_size = $POST_MAX_SIZE/g" /etc/php/8.4/fpm/php.ini
sudo sed -i "s/^upload_max_filesize = 2M/upload_max_filesize = $UPLOAD_MAX_FILESIZE/g" /etc/php/8.4/fpm/php.ini

# Set max processing children for php
sudo sed -i "s/^pm = dynamic/pm = ondemand/g" /etc/php/8.4/fpm/pool.d/www.conf
sudo sed -i "s/^pm.max_children = 5/pm.max_children = $PM_MAX_CHILDREN/g" /etc/php/8.4/fpm/pool.d/www.conf

# Start php-fpm
sudo systemctl restart php8.4-fpm

# MariaDB
sudo systemctl enable --now mariadb
# Secure MariaDB
printf "$MYSQL_ROOT_PASS\nn\nY\n$MYSQL_NEW_PASS\n$MYSQL_NEW_PASS\nY\nY\nY\nY\n" | sudo mariadb-secure-installation

sudo mysql <<EOF
CREATE DATABASE wordpress;
CREATE USER 'wordpress'@'localhost' IDENTIFIED BY '$MYSQL_NEW_PASS';
GRANT ALL PRIVILEGES ON wordpress.* TO 'wordpress'@'localhost';
EOF

# WordPress
curl https://wordpress.org/latest.zip -o /tmp/wordpress.zip
printf "A\n" | sudo unzip -o -q -d /var/www/html /tmp/wordpress.zip
sudo chown -R www-data:www-data /var/www/html/wordpress

sudo cp /var/www/html/wordpress/wp-config-sample.php /var/www/html/wordpress/wp-config.php

sudo sed -i "s|define( 'DB_NAME', 'database_name_here' );|define( 'DB_NAME', '$WORDPRESS_DATABASE_NAME' );|" /var/www/html/wordpress/wp-config.php
sudo sed -i "s|define( 'DB_USER', 'username_here' );|define( 'DB_USER', 'root' );|" /var/www/html/wordpress/wp-config.php
sudo sed -i "s|define( 'DB_PASSWORD', 'password_here' );|define( 'DB_PASSWORD', '$MYSQL_NEW_PASS' );|" /var/www/html/wordpress/wp-config.php