#!/bin/sh

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

ymcMysqlBackupKeepBackups_structure=14

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

backupDir=$(get_structure_backup_dir)
if [ $? -ne 0 ]; then
  ymc_error_msg "Can not get a valid backup-dir for structure-dump"
  exit 1
fi

currentBackupFile="$backupDir/structure_only_$(date -I).sql"
if [ ! -e "$backupDir" ]; then
  mkdir -p $backupDir
fi
if [ ! -f "$currentBackupFile" ]; then
  database_to_dump_schema=$(echo $(echo "show databases;" | mysql -u "$ymcMysqlBackupUser" -p"$ymcMysqlBackupPassword" --skip-column-names | grep -v -E -e '^(mysql|information_schema|performance_schema|lost.found)$'))
  if [ -z "$database_to_dump_schema" ]; then
    database_option="--all-databases"
    ymc_warning_msg "No or empty list of databases retrieved - falling back to dumping all databases using option '$database_option' with mysqldump..."
  else
    database_option="--databases $database_to_dump_schema"
  fi

  mysqldump -u "$ymcMysqlBackupUser" -p"$ymcMysqlBackupPassword" --no-data --no-create-db --skip-add-drop-table $database_option | \
    sed -r 's/^CREATE TABLE /CREATE TABLE IF NOT EXISTS /' | \
    sed -r 's|^/\*!50001 CREATE TABLE |/*!50001 CREATE TABLE IF NOT EXISTS |' | \
    sed -r 's|^/\*!50001 CREATE ALGORITHM=|/*!50001 CREATE OR REPLACE ALGORITHM=|' | \
    sed -r 's/ AUTO_INCREMENT=[0-9]+ / /' > $currentBackupFile
else
  ymc_warning_msg "Not creating backup, as there is already one at '$currentBackupFile'"
fi

ymc_info_msg "Cleaning up old backups..."
oldBackupFileIndex=0
for oldFile in $(ls $backupDir | sort -r); do
  if [ $oldBackupFileIndex -ge $ymcMysqlBackupKeepBackups_structure ]; then
    ymc_info_msg "Removing: $backupDir/$oldFile"
    rm -f $backupDir/$oldFile
  fi
  oldBackupFileIndex=$(expr $oldBackupFileIndex + 1)
done
