#!/bin/bash
# TT#99051: check that tables use InnoDB

set -e

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

request_confirmation() {
  if [[ "${FORCE_UPGRADE}" = "true" ]] ; then
    echo "ERROR: Forcing to STOP, as FORCE_UPGRADE is set" >&2
    exit 1
  fi

  while true; do
    echo -n "Should we continue here? (yes/no): "
    read -r a
    case "${a,,}" in
      yes)
        echo "Continue as requested."
        break
        ;;
      no)
        echo "Aborted as requested." >&2
        exit 1
        ;;
      * )
        echo "Please answer 'yes' or 'no'."
        ;;
    esac
    unset a
  done
}

declare -a db_opts
db_opts+=("--defaults-extra-file=/etc/mysql/sipwise_extra.cnf")
db_opts+=("-h${PAIR_DBHOST}")
db_opts+=("-P${PAIR_DBPORT}")
db_opts+=("-Bs")
db_opts+=("--table")

# Preliminary checks
if ! timeout 5 mysql "${db_opts[@]}" -e "SELECT NOW()" &>/dev/null ; then
  echo "ERROR: Failed to connect to MariaDB"
  exit 1
fi

tmpfile=$(mktemp)
query="SELECT TABLE_SCHEMA as DbName,TABLE_NAME as TableName,ENGINE as Engine FROM information_schema.TABLES WHERE ENGINE != 'InnoDB' AND TABLE_SCHEMA NOT IN('syslog','mysql','information_schema','performance_schema');"

timeout 5 mysql "${db_opts[@]}" -e "${query}" &> "${tmpfile}"
if [[ -s "${tmpfile}" ]] ; then
  echo "Warning: there are tables that we care about with engine different from 'InnoDB':"
  echo
  cat "${tmpfile}"
  echo
  echo "These tables in principle are not supported and are known to cause errors"
  echo "during upgrades, so it is better to take corrective action and fix them."
  echo
  echo "The engine of a table can be changed with:"
  echo
  echo "  alter table <table> engine = InnoDB;"
  echo
  echo "These auto-generated commands can help, but please be careful and check"
  echo "that they match the table above, this code is not battle-tested:"

  echo
  declare -a tables
  mapfile -t tables < <(awk '/^\| [a-z]/ {print $2"."$4}' "${tmpfile}")
  for t in "${tables[@]}"; do
    echo "  alter table ${t} engine = InnoDB;"
  done

  echo
  request_confirmation
else
  echo "OK, all tables that we care about seem to have engine 'InnoDB', nothing to do."
fi

rm -f "${tmpfile}"
