#!/bin/bash
# TT#22004: execute mysql_upgrade after DB upgrade
# MT#58421

set -e

# check connection with sipwise user
if ! mysql --defaults-extra-file="/etc/mysql/sipwise_extra.cnf" -e 'SELECT 1;' &>/dev/null ; then
  echo 'ERROR: cannot connect to local MySQL with sipwise user' >&2
  exit 1
fi

# mysql_upgrade can be already running if automatically
# started after mariadb startup.
TRY=120
while pgrep mysql_upgrade &>/dev/null ; do
  if [[ ${TRY} -gt 0 ]] ; then
    TRY=$((TRY-1))
    echo "Waiting for mysql_upgrade to finish (${TRY} seconds)..."
    sleep 1
  else
    echo "ERROR: mysql_upgrade is still running!" >&2
    exit 1
  fi
done

if mysql_upgrade --defaults-extra-file="/etc/mysql/sipwise_extra.cnf" --force ; then
  echo "mysql_upgrade has been executed successfully"
else
  echo "ERROR: mysql_upgrade has failed, see the error above." >&2
  exit 1
fi
