#!/bin/bash
#Script for SecureTransport - Restore online MySQL backup with Parcona XtraBackup
#Created by Genata 2019

FDH=/opt/Axway/SecureTransport
hd=/root/percona-xtrabackup-2.4.13-Linux-x86_64/bin/
ld=/percona/logs
#Location where backups were greated
bd=/percona/backup

mdd=`cat "$FDH/conf/mysql.conf" |grep datadir | cut -d "=" -f2`
bmd=mysql_`date +%F`

if [ ! -d "$bd/prep" ]; then
  echo Backup ready for restore does not exist. Please use percona_prepare.sh first.
  exit 1
fi

pb=`cat $bd/prep_date 2>/dev/null`
if [ -z "$pb" ]; then
  echo Prepared backup could not be determined. Please use percona_prepare.sh first.
  exit 2
fi

if [ -d "$bd/$bmd" ]; then
  while true; do
    read -p "Backup directory $bd/$bmd exist and will be overwritten. 
Do you want to continue? [y/N]" yn
    case $yn in
      [Yy]* ) rm -r -f $bd/$bmd 2>/dev/null; break;;
      [Nn]* ) exit;;
      * ) exit;;
    esac
  done
fi

hn=`uname -n`
bhn=`cat $bd/prep/backup_hostname 2>/dev/null`
if [ "$hn" != "$bhn" ]; then
  while true; do
    read -p "Hostname of the current machine \"$hn\" differ from the hostname of the machine where backup was created \"$bhn\". 
In a Cluster environment create a backup for each node separately and upon restore make sure you are restoring it on the same server. 
Some configuration options are node specific and database contains node ID in a table ConfigurationOption. 
If you restore database on a wrong node ST will start but will not find specific options for current node and will not work properly.
Do you want to continue? [y/N]" yn
    case $yn in
      [Yy]* ) break;;
      [Nn]* ) exit;;
      * ) exit;;
    esac
  done
fi

echo Restore start... 
echo "[`date -Iseconds`]" Restore start... >>$ld/ST_percona_restore.log

mpid=`ps -ef | grep mysql | grep -v grep | awk '{print $2}' | tr "\n" " "`
if [ ! -z "$mpid" ]; then
  $FDH/bin/stop_all
fi
mpid=`ps -ef | grep mysql | grep -v grep | awk '{print $2}' | tr "\n" " "`
if [ ! -z "$mpid" ]; then
  echo kill -9 $mpid
fi

cp -r $mdd $bd/$bmd
echo Backup of $mdd to $bd/$bmd finished.
echo "[`date -Iseconds`]" Backup of $mdd to $bd/$bmd finished. >>$ld/ST_percona_restore.log

rm -r -f $mdd
mkdir -p $mdd
${hd}xtrabackup --defaults-file=$FDH/conf/mysql.conf --copy-back --target-dir="$bd/prep" >>$ld/ST_percona_restore_xtrabackup.log 2>&1
pxe=$?
if [ $pxe -eq 0 ]; then
  echo Restore of backup from $pb finished successfully.
  echo "[`date -Iseconds`]" Restore of backup from $pb finished successfully. >>$ld/ST_percona_restore.log
else
  echo Error restoring backup from $pb. xtrabackup exit code: $pxe. Rollback to previous version of database from $bd/$bmd ...
  echo "[`date -Iseconds`]" Error restoring backup from $pb. xtrabackup exit code: $pxe. Rollback to previous version of database from $bd/$bmd ... >>$ld/ST_percona_restore.log
  rm -r -f $mdd
  mkdir -p $mdd
  cp -r $bd/$bmd/* $mdd
fi

echo Restore done.
echo "[`date -Iseconds`]" Restore done. >>$ld/ST_percona_restore.log

exit 0
