#!/bin/sh

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

ymc_mysql_user='root'
if [ $(echo "$*" | grep -c '\--no-interaction') -eq 0 ]; then
  no_interaction='no'
else
  no_interaction='yes'
fi

ymc_mysql_tools_get_credentials || exit 1


### Check if we have been advised to not import any data
if [ $(cat $(get_replication_information_dir)/simple.fresh | grep -c "$(get_own_db_service)=manual") -gt 0 ]; then
  echo "INFO: This server needs a manual data import...not auto-importing anything!"
  exit 0
fi

### Check if we need fresh
if [ $(cat $(get_replication_information_dir)/simple.fresh | grep -c "$(get_own_db_service)=fresh") -gt 0 ]; then
  echo "INFO: This server has been advised to replicate from a freshly installed server...doing that!"
  ymc-mysql-setup-replication-from-freshly-installed-mysql-master || exit 1
  exit 0
fi


### Check what kind of mysql we have...
backup_source_hostname=$(get_backup_source_hostname)
if [ $? -eq 0 ] && \
   [ "$backup_source_hostname" != '' ] && \
   [ "$backup_source_hostname" != 'UNDEFINED' ]; then
  echo "USING '$backup_source_hostname' as backup-source..."
else
  echo "INFO: This can only be run on XYZ-mysql-[ro|rw|bu|mi] servers"
  exit 0
fi


final_backup_dir=$(find_maatkit_import_dir $backup_source_hostname)
if [ $? -ne 0 ] || \
   [ ! -d "$final_backup_dir" ]; then
  echo "ERROR: The directory '$final_backup_dir' can not be used as a backup-source - not importing data!"
  exit 1
fi


echo "IMPORTING MYSQL-LIVE-BACKUP-DATA...This might take a long time!"


### Just to make sure...
addToMySQL 'stop slave;'
echo "Slave-thread stopped..."

### Import data using the maatkit-backups
echo "Using backup-dir: $(find_maatkit_import_dir $backup_source_hostname)"
/usr/bin/ymc-mk-parallel-restore --verbose --verbose --tab --createdb --ignoredb=mysql,information_schema,performance_schema --user=$ymc_mysql_user $ymc_mysql_pw_option $final_backup_dir

### Create tables not covered by maatkit
echo "Importing additional tables from: $(find_sql_structure_file $backup_source_hostname)"
mysql -u $ymc_mysql_user $ymc_mysql_pw_option < $(find_sql_structure_file $backup_source_hostname)

### Set the slave-status
echo "Setting slave status from: $(find_maatkit_import_dir $backup_source_hostname)/00_master_data.sql"
mysql -u $ymc_mysql_user $ymc_mysql_pw_option < $(find_maatkit_import_dir $backup_source_hostname)/00_master_data.sql

ymc_mysql_set_replication_auth

### Start the slave
addToMySQL 'start slave;'

