#!/bin/bash
#Nifty: Install Percona Server 8.x from Percona repository

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

# Requirements
require_root
require_os alma8 alma9 alma10

ce "Retrieving list of available versions"
RETRIES=0
while :; do
  # Note that sort -rhu causes some versions to be lost, thus we use uniq
  readarray -t MYSQL_VERSIONS <<< "$(curl -Ssf https://repo.percona.com/|grep -oP 'ps-[8-9][0-9]+(|-lts)\/'| sed 's:/*$::;s/ps-//g' | sort -rh | uniq)"
  [ "${#MYSQL_VERSIONS[@]}" -gt "0" ] && break

  err "Failed to get repository index from https://repo.percona.com"
  [ "$RETRIES" -gt "2" ] && exit 1
  err "Retrying in 3 seconds..."
  RETRIES="$((RETRIES+1))"
  sleep 3
done

if ! is_interactive; then
  MYSQL_VERSION="${MYSQL_VERSIONS[0]}"
else
  echo "The following releases are available for installation: $(implode ", " "${MYSQL_VERSIONS[@]}")"
  MYSQL_VERSION="$(prompt_select_num_value "Which MySQL release would you like to install?" "${MYSQL_VERSIONS[@]}")"
fi

ce "Updating the system packages..."
dnf update -y

ce "Installing EPEL"
dnf install epel-release yum-utils binutils -y

ce "Installing Percona repository"
rpm -Uvh https://repo.percona.com/yum/percona-release-latest.noarch.rpm

ce "Installing MySQL percona-$MYSQL_VERSION"
percona-release setup ps"$MYSQL_VERSION"

ce "Installing required packages"
dnf -y install percona-server-server

ce "Enabling MySQL on startup"
systemctl enable mysqld

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

MYSQL_PASSWORD="$(random_string 16)"

ce "Setting up MySQL (my.cnf)"
cat <<EOF > /etc/my.cnf
# Client configs
[mysql]
port                           = 3306
socket                         = /var/lib/mysql/mysql.sock

# Server configs
[mysqld]
user                           = mysql
default-storage-engine         = InnoDB
socket                         = /var/lib/mysql/mysql.sock
pid-file                       = /var/lib/mysql/mysql.pid
datadir                        = /data/mysql

# MyISAM
key-buffer-size                = 32M

# Safety things
max-allowed-packet             = 16M
max-connect-errors             = 1000000
skip-name-resolve

# Cache and limitations
tmp-table-size                 = 32M
max-heap-table-size            = 32M
max-connections                = 500
thread-cache-size              = 50
open-files-limit               = 20000
table-definition-cache         = 4096
table-open-cache               = 5000

# InnoDB Settings (Buffer pool default: 50% memory)
innodb-flush-method            = O_DIRECT
innodb_redo_log_capacity       = 256M
innodb-flush-log-at-trx-commit = 2
innodb-file-per-table          = 1
innodb-buffer-pool-size        = $NIFTY_MYSQL_INNODB_BUFFER_SIZE


# Binary logging (set to 1 day)
binlog-expire-logs-seconds     = 86400
skip-log-bin

EOF

ce "Wiping MySQL data"
mkdir -p /var/lib/mysql
rm -rf /var/lib/mysql/*
chown -R mysql: /var/lib/mysql

ce "Prepping data directory"
mkdir -p /data/mysql
chown mysql: /data/mysql

mysqld --initialize >> /var/log/mysqld.log 2>&1
chown -R mysql:mysql /data/mysql

sleep 2
TEMP_MYSQL_PASSWORD=$(grep "A temporary password is generated for root" /var/log/mysqld.log | rev | cut -d" " -f1 | rev | tail -n 1)
ce "Set OOM Kill value for MySQL to -1000"
mkdir -p /etc/systemd/system/mysqld.service.d
cat <<EOF > /etc/systemd/system/mysqld.service.d/override.conf
[Service]
OOMScoreAdjust=-1000
EOF
systemctl daemon-reload

ce "Starting MySQL"
systemctl start mysqld

ce "Setting MySQL root password"
mysql -e "ALTER USER 'root'@'localhost' IDENTIFIED BY '$MYSQL_PASSWORD';" -uroot -p"$TEMP_MYSQL_PASSWORD" --connect-expired-password
echo "$MYSQL_PASSWORD" > /root/.mysql
chmod 400 /root/.mysql

ce "How to do backups?"
ce " 1 ) Install DBCloney (default)"
ce " 2 ) Install legacy script"
ce " 3 ) No backup"
echo -n "Your choice [1]: "
read -r choice

if [ "$choice" = "" ] || [ "$choice" = "1" ] ; then
  ce "Install DBCloney"
  bash <(curl -s https://nifty.sh/install/universal/dbcloney.sh)
elif [ "$choice" = "2" ]; then
	echo "Install Legacy Backup"
  bash <(curl -s https://nifty.sh/install/universal/mysqlbackup.sh)
else
	echo "No backup or invalid choice given"
	echo "Will not install any backup"
fi

echo -en "\n\n\n"
ce "All done!"
