#!/bin/sh

. /usr/lib/lib-ymc/ymc-mysql-tools.sh || exit 1


ymcMysqlBackupKeepBackups_maatkit=14
ymcMysqlTemporaryLocalBackupDir="/tmp/ymc-mysql-backup/local_backup_generator"

### Source our config...
. $(get_replication_information_dir)'/simple.restore'


nfsBackupDir=$(get_maatkit_backup_dir)
if [ $? -ne 0 ]; then
  ymc_error_msg "Can not get a valid backup-dir for maatkit"
  exit 1
fi

localBackupDir="$ymcMysqlTemporaryLocalBackupDir/maatkit"

currentLocalBackupDir="$localBackupDir/$(date -I)/"
currentNfsBackupDir="$nfsBackupDir/$(date -I)/"

if [ ! -d "$nfsBackupDir" ]; then
  mkdir -p $nfsBackupDir
fi

if [ ! -d "$nfsBackupDir" ]; then
  echo "Failed to create nfs-backup-base-dir at '$nfsBackupDir'"
  exit 1
fi

if [ -e "$currentLocalBackupDir" ]; then
  echo "Not doing a backup, as there is already a local-backup-dir at '$currentLocalBackupDir'"
  exit 1
fi

if [ -e "$currentNfsBackupDir" ]; then
  echo "Not doing a backup, as there is already a nfs-backup-dir at '$currentNfsBackupDir'"
  exit 1
fi

mkdir -p $currentLocalBackupDir
if [ ! -e "$currentLocalBackupDir" ]; then
  echo "Failed to create a local-backup-dir at '$currentLocalBackupDir'"
  exit 1
fi

ymcBackupThreadsOption=""
if [ -n "$ymcMysqlParallelBackupThreadsToUse" ]; then
  ymcBackupThreadsOption="--numthread $ymcMysqlParallelBackupThreadsToUse"
fi

echo "STOP SLAVE;" | mysql -u "$ymcMysqlBackupUser" -p"$ymcMysqlBackupPassword"
if [ $? -ne 0 ]; then
  echo "FAILED TO STOP THE SLAVE!"
  exit 1
fi

if [ -n "$ymcMysqlBackupIgnoreTable_maatkit" ]; then
  ignore_table_string=""
  for table_to_ignore in $(echo $ymcMysqlBackupIgnoreTable_maatkit | sed -r 's/,/ /g')
  do
    ignore_table_string="$ignore_table_string,$table_to_ignore"
  done
  ignore_table_string="--ignoretbl=$(echo $ignore_table_string | sed -r 's/^,//')"
else
  ignore_table_string=""
fi

/usr/bin/ymc-mk-parallel-dump --verbose --verbose $ymcBackupThreadsOption --gzip --binlogpos --flushlog --flushlock --charset=utf8 --user="$ymcMysqlBackupUser" --password="$ymcMysqlBackupPassword" --basedir=$currentLocalBackupDir --ignoredb=information_schema,performance_schema $ignore_table_string
if [ $? -ne 0 ]; then
  echo "Failed to generate the backup in '$currentLocalBackupDir'"
  exit 1
fi
echo "START SLAVE;" | mysql -u $ymcMysqlBackupUser -p"$ymcMysqlBackupPassword"
if [ $? -ne 0 ]; then
  echo "FAILED TO START THE SLAVE!"
  exit 1
fi

mv $currentLocalBackupDir $currentNfsBackupDir
if [ $? -ne 0 ]; then
  echo "Failed to move backup into nfs (from '$currentLocalBackupDir' to '$currentNfsBackupDir')"
  exit 1
fi


echo "Cleaning up old backups from NFS..."
oldBackupDirIndex=0
for oldDir in $(ls $nfsBackupDir | sort -r); do
  if [ $oldBackupDirIndex -ge $ymcMysqlBackupKeepBackups_maatkit ]; then
    echo "Removing: $nfsBackupDir/$oldDir"
    rm -rf $nfsBackupDir/$oldDir
  fi
  oldBackupDirIndex=$(expr $oldBackupDirIndex + 1)
done
