#!/usr/bin/env bash

# For this script, all the following is doing is setting all variables except LOCAL_RESTORE, which would only be set if run with an argument.
# Otherise its: $(mktemp -d /tmp/mysql.XXXXXXXXXX)/restore"
. /src/oddjob/mariadb/backup_lib.sh

if [ "n${1}" != "n" ]; then
  LOCAL_RESTORE=$1;
else
  LOCAL_RESTORE=$RESTORE_DIR;
fi

if [[ ! -d $LOCAL_RESTORE || ! -d "${LOCAL_RESTORE}/mysql" ]]; then
  echo "${LOCAL_RESTORE} is either not a directory, or doesn't contain a mysql database"
  exit 1
fi;

sudo mariabackup --prepare --target-dir=$LOCAL_RESTORE
MYSQL_PID=$(pgrep mariadb)
if [ "n${MYSQL_PID}" != "n" ]; then
  sudo kill -9 $MYSQL_PID;
fi
sudo rm -rf $MYSQL_DIR/* $MYSQL_LOG_DIR/*
sudo mariabackup --move-back --target-dir=$LOCAL_RESTORE
sudo chown -R mysql:mysql $MYSQL_DIR $MYSQL_LOG_DIR
sudo service mariadb start
