#!/bin/bash
# Disable MariaDB tables encryption (binlogs,redo logs remain encrypted)

set -euEo pipefail

DELAY=1

# === FUNCTIONS =========================================================

die() {
  local message="$*"

  echo "ERROR: ${message}" >&2
  exit 1
}

fatal_missing_var() {
  local var_name="$1"
  local var_value="${!var_name}"

  if [[ -z "${var_value}" ]] ; then
    die "Missing mandatory environment variable '\$${var_name}', exiting."
  fi
}

# === MAIN ==============================================================

fatal_missing_var CARRIER_EDITION

if [ ! -f /etc/default/ngcp-roles ] ; then
  die "Missing mandatory file '/etc/default/ngcp-roles', cannot continue!"
fi

# shellcheck disable=SC1091
. /etc/default/ngcp-roles

fatal_missing_var NGCP_IS_PROXY
fatal_missing_var NGCP_IS_LI

count_encrypted_table_sql="SELECT COUNT(1) FROM information_schema.INNODB_TABLESPACES_ENCRYPTION WHERE encryption_scheme = 1"
increase_encryption_threads_sql="SET GLOBAL innodb_encryption_threads = 8"
disable_tables_encryption="SET GLOBAL innodb_encrypt_tables = OFF"
disable_innodb_fast_shutdown="SET GLOBAL innodb_fast_shutdown = 0"

echo "Increase MariaDB:3306 encryption threads 1 to 8"
mysql -e "${increase_encryption_threads_sql}"
echo "Set MariaDB:3306 innodb_fast_shutdown to 0"
mysql -e "${disable_innodb_fast_shutdown}"
echo -n "Disabling MariaDB:3306 tables encryption (auto re-enabled after restart)..."
mysql -e "${disable_tables_encryption}"
while true; do
  ENCRYPTED_TABLES_CNT=$(mysql -N -s -e "${count_encrypted_table_sql}")
  if [[ "${ENCRYPTED_TABLES_CNT}" -eq 0 ]]; then
    break
  fi
  sleep "${DELAY}"
done
echo " done"

if ! "${CARRIER_EDITION}"; then
  exit 0
fi

if [[ "${NGCP_IS_PROXY}" != "yes" && "${NGCP_IS_LI}" != "yes" ]] ; then
  exit 0
fi

EXTRA_ARGS="-S/run/mysqld/mysqld2.sock"
echo "Increase MariaDB:3308 encryption threads 1 to 8"
mysql "${EXTRA_ARGS}" -e "${increase_encryption_threads_sql}"
echo "Set MariaDB:3308 innodb_fast_shutdown to 0"
mysql "${EXTRA_ARGS}" -e "${disable_innodb_fast_shutdown}"
echo -n "Disabling MariaDB:3308 tables encryption (auto re-enabled after restart)..."
mysql "${EXTRA_ARGS}" -e "${disable_tables_encryption}"
while true; do
  ENCRYPTED_TABLES_CNT=$(mysql -N -s "${EXTRA_ARGS}" -e "${count_encrypted_table_sql}")
  if [[ "${ENCRYPTED_TABLES_CNT}" -eq 0 ]]; then
    break
  fi
  sleep "${DELAY}"
done
echo " done"
