#!/bin/bash
#Nifty: Install and configure DBCloney from internal repository

set -e

# Source niftylib
curl -s https://nifty.sh/lib/universal/niftylib.sh > /tmp/lib.nifty.sh
. /tmp/lib.nifty.sh
rm -f /tmp/lib.nifty.sh

# Requirements
require_root
require_64bit
require_os alma10 alma9 centos9 alma8 centos8 centos7

OS="$(detect_os)"

require_cmd mysql

# Configure team.blue repository
REPO_FILE="/etc/yum.repos.d/teamblue_saferepo.repo"
if [ ! -f "$REPO_FILE" ]; then
  ce "Safe repository is not configured on this server."
  ce "If this server is managed by puppet, add the tbn_repository manifest in Netadmin."
  ce "If this server is NOT managed by puppet, answer yes below."
  ce

  read -n 1 -p 'Install saferepo manually? (Y/N)' INSTALL_REPO
  echo
  if [ "${INSTALL_REPO,,}" != "y" ]; then
    err "Saferepo not installed. Please install it and run this script again."
    exit 1
  fi

  ce "Installing team.blue safe repository"
  OS_RELEASE="$(tr -dc '[:digit:]' <<< "$OS")"

  tee <<EOF > "$REPO_FILE"
[teamblue_saferepo]
name=team.blue yum repo
baseurl=https://repo.dk.team.blue/centos/${OS_RELEASE}/x86_64
gpgkey=https://repo.dk.team.blue/centos/${OS_RELEASE}/x86_64/RPM-GPG-KEY-teamblue
enabled=True
gpgcheck=1
EOF
fi

# Try to guess MySQL root credentials
if [ -f "/etc/psa/.psa.shadow" ]; then
  MYSQL_PASS="$(cat "/etc/psa/.psa.shadow")"
  CMD="/usr/bin/mysql -uadmin -p$MYSQL_PASS"
elif [ -f "/root/.mysql" ]; then
  MYSQL_PASS="$(cat "/root/.mysql")"
  CMD="/usr/bin/mysql -uroot -p$MYSQL_PASS"
elif [ -f "/root/.my.cnf" ]; then
  CMD="/usr/bin/mysql --defaults-extra-file=/root/.my.cnf"
fi

if [ -z "$CMD" ]; then
  err "Failed to find MySQL root password automatically."
  printf "MySQL root password: "
  read -r MYSQL_PASS
  CMD="/usr/bin/mysql -uroot -p$MYSQL_PASS"
fi

# Test the credentials
while ! $CMD -e "SELECT NULL;" > /dev/null; do
  printf "MySQL root password: "
  read -r MYSQL_PASS
  CMD="/usr/bin/mysql -uroot -p$MYSQL_PASS"
done

# Create a MySQL user for DBCloney and save the details
ce "Creating MySQL user"
mkdir -p /etc/dbcloney
if [ -n "$CMD" ] && [ ! -f "/etc/dbcloney/my.cnf" ]; then
  # Determine MySQL version
  MYSQL_VERSION="$($CMD -NB -e 'SELECT @@version')"
  MYSQL_NEW_PASS="$(head -c100 /dev/urandom | tr -dc "A-Za-z0-9" | head -c32)"

  case "$MYSQL_VERSION" in
    "5.5"*|"5.6"*)
      $CMD -e 'GRANT USAGE ON *.* TO mysqlbackup@127.0.0.1;'
      $CMD -e 'DROP USER mysqlbackup@127.0.0.1;'
      PASSWORD_QUERY='CREATE USER mysqlbackup@127.0.0.1 IDENTIFIED BY "'"$MYSQL_NEW_PASS"'";'
    ;;
    "5.7."*|"8."*)
      $CMD -e 'DROP USER IF EXISTS mysqlbackup@127.0.0.1;'
      PASSWORD_QUERY='CREATE USER mysqlbackup@127.0.0.1 IDENTIFIED WITH mysql_native_password BY "'"$MYSQL_NEW_PASS"'"'
    ;;
    "10."*)
      $CMD -e 'DROP USER IF EXISTS mysqlbackup@127.0.0.1;'
      PASSWORD_QUERY='CREATE USER mysqlbackup@127.0.0.1 IDENTIFIED BY "'"$MYSQL_NEW_PASS"'";'
  esac

  while ! $CMD -e "$PASSWORD_QUERY"; do
    echo "User creation failed, see the above warning. If denied by password policy, please provide a random password below."
    printf "Backup user MySQL password: "
    read -r MYSQL_NEW_PASS
  done

  case "$MYSQL_VERSION" in
    "8."*) $CMD -e 'GRANT SHOW DATABASES, SELECT, CREATE, CREATE TABLESPACE, INSERT, REPLICATION CLIENT, LOCK TABLES, SUPER, BACKUP_ADMIN, RELOAD, PROCESS, SHOW VIEW ON *.* TO mysqlbackup@127.0.0.1;' ;;
    *) $CMD -e 'GRANT SHOW DATABASES, SELECT, CREATE, CREATE TABLESPACE, INSERT, REPLICATION CLIENT, LOCK TABLES, SUPER, RELOAD, PROCESS, SHOW VIEW ON *.* TO mysqlbackup@127.0.0.1;' ;;
  esac

  tee <<EOF > /etc/dbcloney/my.cnf
[mysql]
user=mysqlbackup
password="$MYSQL_NEW_PASS"
host=127.0.0.1
port=3306
[mysqldump]
user=mysqlbackup
password="$MYSQL_NEW_PASS"
host=127.0.0.1
port=3306
[xtrabackup]
user=mysqlbackup
password="$MYSQL_NEW_PASS"
host=127.0.0.1
port=3306
EOF
fi

# Install the DBCloney package
ce "Installing DBCloney"
yum clean all
yum install dbcloney-client -y
chown -R mysqlbackup: /etc/dbcloney
chmod 600 /etc/dbcloney/my.cnf

# Register the client and dump default configuration
ce "Registering client"
if ! dbcloney register; then
  err "DBCloney client registration failed. Exiting."
  err 'When the above issue is resolved, please run `dbcloney register` to retry registration.'
  exit 1
fi

ce "=============================="
ce "DBCloney registered successfully with the following options:"
cat /etc/dbcloney/options.json

ce "Please ensure that the above options are correct and perform a test run with \"dbcloney run\"."
