#!{{ dash }}

# DO NOT RUN THIS SCRIPT ON PRODUCTION INSTANCE
# OR MYSQL DATA WILL BE ERASED.

# This script will import the dump of the mysql database to the real
# database. It is launched by the clone (importer) instance of webrunner
# in the end of the import script.

# Depending on the output, it will create a file containing
# the status of the restoration (success or failure)

set -e

mysql_executable='{{ mysql_executable }}'
mariadb_data_directory='{{ mariadb_data_directory }}'
mariadb_backup_directory='{{ mariadb_backup_directory }}'
pid_file='{{ pid_file }}'
binlog_path='{{ binlog_path }}'
server_executable='{{ server_executable }}'
update_executable='{{ update_executable }}'

# Make sure mariadb is not already running
if [ -e "$pid_file" ]; then
  pid=$(cat "$pid_file")
  if [ $? -ne 0 ]; then
    echo "Cannot read Mariadb pidfile, assuming running. Aborting."
    exit 1
  fi
  if kill -0 "$pid"; then
    echo "Mariadb is already running with pid $pid. Aborting."
    exit 1
  fi
fi

echo "Deleting existing database..."
rm -r "$mariadb_data_directory"/* >/dev/null 2>&1 || true

# $binlog_path can be empty if incremental_backup_retention_days <= -1
if [ -n "$binlog_path" ]; then
  new_binlog_directory="$(dirname "$binlog_path")"
  binlog_index_file="$new_binlog_directory/binlog.index"
  if [ -e "$binlog_index_file" ]; then
    echo "Adapting binlog database to new paths..."
    old_binlog_directory="$(dirname $(head -n 1 $binlog_index_file))"
    sed -e "s|$old_binlog_directory|$new_binlog_directory|g" $binlog_index_file > $binlog_index_file
  fi
fi

echo "Starting mariadb..."
"$server_executable" --innodb-flush-method=nosync --skip-innodb-doublewrite --innodb-flush-log-at-trx-commit=0 --sync-frm=0 --slow-query-log=0 --skip-log-bin &
mysqld_pid=$!
trap "kill $mysqld_pid" EXIT TERM INT
sleep 30
# If mysql has stopped, abort
if ! [ -d /proc/$mysql_pid ]; then
  echo "mysqld exited, aborting."
  exit 1
fi
"$update_executable" &
mariadb_update_pid=$!
sleep 60
# If mariadb_update is still running, abort
if [ -d /proc/$mariadb_update_pid ]; then
  echo "mariadb_update still running after timeout, aborting."
  kill $mariadb_update_pid
  exit 1
fi

echo "Importing data..."
# Use latest dump XXX can contain funny characters
dump=$(ls -r "$mariadb_backup_directory" | head -1)
zcat "$mariadb_backup_directory/$dump" | $mysql_executable -u root
RESTORE_EXIT_CODE=$?

if [ $RESTORE_EXIT_CODE -eq 0 ]; then
  echo 'Backup restoration successfully completed.'
else
  echo 'Backup restoration failed.'
fi

exit $RESTORE_EXIT_CODE
