#!/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 a fresh slave to start replication from a fresh master
if [ $(addToMySQL "show slave status;" | grep -c 'Master_Host') -gt 0 ]; then
  echo "ERROR: Can not setup a fresh replication on a configured slave."
  echo "       Please DROP any existing replicated database and 'RESET' the slave manually!"
  exit 1
fi


### Get our (fresh) master
master_host=$(get_master_service_type)
if [ $? -ne 0 ] || \
   [ "$master_host" = '' ]; then
  echo "ERROR: The master-host '$master_host' seems to be invalid!"
  exit 1
fi

echo "SETTING UP FRESH REPLICATION FROM '$master_host'..."
addToMySQL "CHANGE MASTER TO MASTER_HOST='$master_host';"

ymc_mysql_set_replication_auth

echo "Starting slave..."
addToMySQL 'start slave;'

exit 0

