#!/bin/bash
#Nifty: Install Plesk with Percona and mysqlbackup

set -e
trap cleanup ERR EXIT

cleanup() {
  if [ -f "/tmp/plesk-installer" ]; then
    rm "/tmp/plesk-installer"
  fi
}

# shellcheck source=../../lib/universal/niftylib.sh
source <(curl -fSs https://nifty.sh/lib/universal/niftylib.sh)

require_root
require_os alma8 alma9 alma10

ce "Installing MySQL"

if [ -z "$NIFTY_MYSQL_INNODB_BUFFER_SIZE" ]; then
  TOTAL_MEMORY="$(get_total_memory)"
  export NIFTY_MYSQL_INNODB_BUFFER_SIZE="$((TOTAL_MEMORY / 4 / 1024))K"
fi

bash <(curl -s "https://nifty.sh/install/universal/percona_server_80.sh")

# Remove the password file created by the Percona installer.
# The password will be changed by Plesk anyway, so it only causes issues.
if [ -f "/root/.mysql" ]; then
  rm "/root/.mysql"
fi

ce "Installing Plesk"

if [ "$(detect_os)" = "alma8" ]; then
  ce "Enabling app stream modules"
  dnf -y module enable python36 python27 perl* nginx:1.20 httpd php
fi

# Do not set 1-2-3-4.plesk.page hostname, if the actual server hostname is non-resolvable during install.
export PLESK_CONFIG__techDomain__hostname__enabled=0

cd /tmp/
wget https://autoinstall.plesk.com/plesk-installer
chmod +x ./plesk-installer
./plesk-installer install plesk \
  --preset Recommended \
  --without dovecot roundcube advisor xovi imunifyav selinux bind \
  --with php8.4

ce "Initializing Plesk"
plesk bin init_conf --init

ADMIN_PASSWORD="$(random_string 16)"
plesk bin init_conf --set-admin-password -passwd "$ADMIN_PASSWORD"

ce "Install the license"
echo "You can get a license from https://tools.zitcom.dk/plesk.php"

while :; do
  echo -n "Paste the license key here: "
  read -r choice
  if /usr/local/psa/bin/license -i "$choice"; then
    break
  fi
done

ce "Fixing Plesk"
echo "Set Plesk default PHP version to PHP 8.4"
plesk bin service_plan -u "Default Domain" -php_handler_id plesk-php84-fpm
plesk bin service_plan -u "Default Simple" -php_handler_id plesk-php84-fpm
plesk bin service_plan -u "Unlimited" -php_handler_id plesk-php84-fpm

echo "Disable Plesk mail service"
plesk bin service_plan -u "Default Domain" -mail false
plesk bin service_plan -u "Default Simple" -mail false
plesk bin service_plan -u "Unlimited" -mail false

echo
ce "Plesk install completed!"
echo
echo "Admin plesk password (to the customer) is: $ADMIN_PASSWORD"
echo
ce "Plesk login link:"
plesk login
