#!/bin/bash

set -eo pipefail

err() {
	>&2 echo "$1"
	exit 1
}

main() {
	if [[ -z "$1" ]]; then
		err "Host name not given or empty!"
	fi

	if [[ ! -d "$2" ]]; then
		err "Backup directory '$2' is invalid!"
	fi

	local readonly SITENAME="$1"
	local readonly SITESAFE=$(echo "${SITENAME}" | tr '.' '_')
	local readonly WPBACKUP=$(find "$2" -type f -name "*.gz" | head -n 1)
	local readonly DBBACKUP=$(find "$2" -type f -name "*.sql" | head -n 1)
	local readonly TARGETBASE="/home/${SITESAFE}"
	local readonly WPTARGET="${TARGETBASE}/${SITENAME}"

	# Load WP configs
	source "$2/config.sh"

	# Create user
	if ! id -u "${SITESAFE}" > /dev/null; then
		adduser --system --group "${SITESAFE}"
	fi

	# Extract WP files
	mkdir -p "${WPTARGET}"
	tar -xf "${WPBACKUP}" --directory "${WPTARGET}" --strip-components 1
	chown -R "${SITESAFE}":"${SITESAFE}" "${WPTARGET}"

	# Setup and restore DB
	echo "Setting up database"
	mysql -u root -p <<- SQL
		DROP USER IF EXISTS '${configValues[DB_USER]}'@'localhost';
		CREATE USER '${configValues[DB_USER]}'@'localhost' IDENTIFIED BY '${configValues[DB_PASSWORD]}';

		DROP DATABASE IF EXISTS ${configValues[DB_NAME]};
		CREATE DATABASE ${configValues[DB_NAME]};
		GRANT ALL ON ${configValues[DB_NAME]}.* TO '${configValues[DB_USER]}'@'localhost';
		USE ${configValues[DB_NAME]};

		SOURCE ${DBBACKUP};
	SQL

	# Setup PHP-FPM
	echo "Setting up PHP FPM"
	cat <<- CONF > /etc/php/7.3/fpm/pool.d/${SITESAFE}.conf
		[${SITESAFE}]
		user = ${SITESAFE}
		group = ${SITESAFE}
		listen = /run/php/php7.3-fpm-${SITESAFE}.sock
		listen.owner = www-data
		listen.group = www-data
		php_admin_value[disable_functions] = exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source,dl,setenv
		php_admin_flag[allow_url_fopen] = off
		; Choose how the process manager will control the number of child processes.
		pm = dynamic
		pm.max_children = 75
		pm.start_servers = 10
		pm.min_spare_servers = 5
		pm.max_spare_servers = 20
		pm.process_idle_timeout = 10s
		env[HOSTNAME] = $HOSTNAME
		env[TMP] = /tmp
	CONF
	if php-fpm7.3 -t; then
	       	service php7.3-fpm restart
	else
		err "Something went wrong with PHP FPM!"
	fi

	# Setting up NGINX
	echo "Setting up NGINX"
	local readonly NGINXCONF="/etc/nginx/sites-available/${SITENAME}"
	cat <<- CONF > "${NGINXCONF}"
		server {
                        listen 80;
                        listen [::]:80;
		        listen 443 ssl;
		        listen [::]:443 ssl;
		
		        server_name ${SITENAME} www.${SITENAME};
		
		        include snippets/wordpress.conf;
		
		        root ${WPTARGET};
		
		        access_log /var/log/nginx/${SITENAME}-access.log;
		        error_log /var/log/nginx/${SITENAME}-error.log error;
		
		        index index.php;
		
		        location / {
		                try_files \$uri \$uri/ /index.php?\$args;
		        }
		
		        location ~ \.php$ {
		                include snippets/fastcgi-php.conf;
		                fastcgi_pass unix:/run/php/php7.3-fpm-${SITESAFE}.sock ;
		        }
		
		        ssl_protocols TLSv1.2 TLSv1.3;
		
		        ssl_stapling on;
		        ssl_stapling_verify on;
		}
	CONF
	ln -s "${NGINXCONF}" /etc/nginx/sites-enabled
	if nginx -t; then
		service nginx restart
	else
		err "Something went wrong while configuring NGINX"
	fi
		
}

main "$@" || exit 1