#!/usr/bin/bash
#
# sm-sync-to-master - Syncs mysql slaves to masters
# Copyright (c) 2016 Joyent Inc., All rights reserved.

set -o errexit
set -o pipefail
#set -o nounset
#set -o xtrace
#export 'PS4=+ $me.$LINENO ';

usage() {
        cat <<- EOF >&2

Usage: $0 [options] MASTER_USER MASTER_PASS MASTER_HOST SLAVE_USER SLAVE_PASS SLAVE_HOST

Options:
    
    None available at this time.

Arguments:
   
    MASTER_USER             User of master host.  Must be a user with SUPER
                            privileges and GRANT option.
    MASTER_PASS             Password of master host user.  (Passwords with
                            special characters must be surrounded in single
                            quotes).
    MASTER_HOST             Host/IP of master. 

    SLAVE_USER              User of slave host (this host).  Must be a user
                            with SUPER privileges.
    SLAVE_PASS              Password of slave host user.  (Passwords with
                            special characters must be surrounded in single
                            quotes).
    SLAVE_HOST              Host/IP of slave (this host).

EOF
exit 2;
}

shift $(($OPTIND - 1))
if [[ $# = 6 ]]; then
        muser="$1";
        mpass="$2";
        mhost="$3";
        suser="$4";
        spass="$5";
        shost="$6";
else
        usage;
fi

export LANG=C
PATH="/opt/local/bin:/opt/local/gnu/bin:/opt/local/sbin:/usr/bin:/usr/sbin";
mhost_dumpfile="/var/tmp/$(date +%Y-%m-%d_%H-%M-%S)-sync.sql";
mhost_repluser="repluser";
mhost_replpass="$(od -An -N9 -x /dev/random | head -1 | tr -d ' ')";

failtest() {
        printf "ERROR.\n\n! $*\n\n" >&2;
	rm ${mhost_dumpfile} 2> /dev/null
        exit 2;
}
mysql_header() {
	printf "\n$(basename $0) - Syncs mysql slaves to masters.\n";
}
mysql_sanitycheck() {
        printf "\n%-70s" "* Sanity checking mysql environment..";

	# Check that we have mysql installed
        hash mysql &> /dev/null
        [[ $? -eq 1 ]] && failtest "mysql was not found in your PATH.";

        hash mysqldump &> /dev/null
        [[ $? -eq 1 ]] && failtest "mysqldump was not found in your PATH.";

	# Check that mysql is running on the slave (this host)
        [[ ! `pgrep mysqld` ]] && failtest "Mysql must be running on the slave host (${shost}).";

	# Check we can connect to the slave host (this host)
        [[ $(mysql -u${suser} -p${spass} -h ${shost} -e "select version();" &> /dev/null)$? -ne 0 ]] && failtest "Unable to connect to slave host (${shost}).  Things to check:\n!\n! Check that you are using the correct user, pass, and host combination.\n! (Passwords with special characters must be surrounded in single quotes).\n!\n! You can verify your conneciton with:\n! # mysql -u${suser} -p${spass} -h ${shost}\n";

	# Check that the slave host has a unique server-id
	shost_serverid=$(mysql -u${suser} -p${spass} -h ${shost} -sN -e "show variables like 'server_id'" 2> /dev/null | awk '{ print $2 }');
	[[ "${shost_serverid}" = "0" ]] && failtest "Slave host (${shost}) doesn't have server-id set to a unique value.";

	# Check that the slave has log-bin turned on
	[[ $(mysql -u${suser} -p${spass} -h ${shost} -sN -e "show variables like 'log_bin'" 2> /dev/null | awk '{ print $2 }') = "OFF" ]] && failtest "Slave host (${shost}) doesn't have log-bin enabled.";

	# Check that we can connect to the master host
        [[ $(mysql -u${muser} -p${mpass} -h ${mhost} -e "select version();" &> /dev/null)$? -ne 0 ]] && failtest "Unable to connect to master host (${mhost}).  Things to check:\n!\n! You are using the correct user, pass, and host combination.\n! (Passwords with special characters must be surrounded in single quotes).\n!\n! The master host is not listening on localhost.\n!\n! You are using a privileged user on the master host.  Create with:\n! mysql> grant all privileges on *.* to 'smsync'@'10.%%' identified by\n! 'password' with GRANT OPTION;\n!\n! You can verify your connection with:\n! # mysql -u${muser} -p${mpass} -h ${mhost}\n";

	# Check that the master host has a unique server-id
	mhost_serverid=$(mysql -u${muser} -p${mpass} -h ${mhost} -sN -e "show variables like 'server_id'" 2> /dev/null | awk '{ print $2 }');
	[[ "${mhost_serverid}" = "0" ]] && failtest "Master host (${mhost}) doesn't have server-id set to a unique value.";

	# Check that the master has log-bin turned on
	[[ $(mysql -u${muser} -p${mpass} -h ${mhost} -sN -e "show variables like 'log_bin'" 2> /dev/null | awk '{ print $2 }') = "OFF" ]] && failtest "Master host (${mhost}) doesn't have log-bin enabled.";

	# Check that the master and slave have unique server-ids
	[[ "${shost_serverid}" = "${mhost_serverid}" ]] && failtest "Master host (${mhost}) and Slave host (${shost}) have the same\n! server-id value (${shost_serverid}).  These values must be unique.\n!\n! Change the 'server-id' value in /opt/local/etc/my.cnf and restart mysql\n! # svcadm restart percona";

        printf "OK.\n";
}
mysql_dumpmaster() {
        printf "%-70s" "* Dumping master host (${mhost}) mysql..";

	mysqldump -u${muser} -p${mpass} -h ${mhost} --master-data=2 -A --ignore-table=mysql.user --ignore-table=mysql.host --ignore-table=mysql.tables_priv --ignore-table=mysql.servers --ignore-table=mysql.db > ${mhost_dumpfile} 2> /dev/null || failtest "There was a problem dumping master (${mhost}) to ${mhost_dumpfile}.";

        printf "OK.\n";
}
mysql_importdump() {
	mhost_dumpfile_size="$(ls -lh ${mhost_dumpfile} | awk '{ print $5 }')";

        printf "%-70s" "* Importing dump (${mhost_dumpfile_size}) to slave host (${shost})..";

	mysql -u${suser} -p${spass} -h ${shost} < ${mhost_dumpfile} 2> /dev/null || failtest "There was a problem importing ${mhost_dumpfile}\n! to slave (${shost}).";

        printf "OK.\n";
}	
mysql_configrepl() {
        printf "%-70s" "* Configuring replication..";

	mysql -u${muser} -p${mpass} -h ${mhost} -sN -e "grant replication slave, replication client on *.* to '${mhost_repluser}'@'10.%' identified by '${mhost_replpass}'" 2> /dev/null || failtest "There was a problem creating the replication user\n! on master host (${mhost}).";

	mysql -u${muser} -p${mpass} -h ${mhost} -sN -e "flush privileges" 2> /dev/null

	mhost_binfile="$(head -40 ${mhost_dumpfile} | grep 'TO MASTER_LOG_FILE' | awk -F\' '{ print $2 }')";
	mhost_binpos="$(head -40 ${mhost_dumpfile} | grep 'TO MASTER_LOG_FILE' | awk -F= '{ print $3 }' | awk -F\; '{ print $1 }')";

	mysql -u${suser} -p${spass} -h ${shost} -sN -e "stop slave" 2> /dev/null
	mysql -u${suser} -p${spass} -h ${shost} -sN -e "reset master" 2> /dev/null
	mysql -u${suser} -p${spass} -h ${shost} -sN -e "reset slave" 2> /dev/null
	mysql -u${suser} -p${spass} -h ${shost} -sN -e "CHANGE MASTER TO master_user='${mhost_repluser}', master_password='${mhost_replpass}', master_host='${mhost}', master_log_file='${mhost_binfile}', master_log_pos=${mhost_binpos}" 2> /dev/null
	mysql -u${suser} -p${spass} -h ${shost} -sN -e "start slave" 2> /dev/null

        printf "OK.\n";
}
mysql_checkrepl() {
        printf "%-70s" "* Checking replication status..";

	shost_logerror=$(mysql -u${suser} -p${spass} -h ${shost} -sN -e "show variables like 'log_error'" 2> /dev/null | awk '{ print $2 }');
	shost_slaveio="$(mysql -u${suser} -p${spass} -h ${shost} -e "show slave status \G" 2> /dev/null | grep 'Slave_IO_Running:' | awk '{ print $2 }')";
	shost_slavesql="$(mysql -u${suser} -p${spass} -h ${shost} -s -e "show slave status \G" 2> /dev/null | grep 'Slave_SQL_Running:' | awk '{ print $2 }')";

	if [[ "${shost_slaveio}" = "Yes" ]] && [[ "${shost_slavesql}" = "Yes" ]]; then
		printf "OK.\n\n";
		printf "Slave host (${shost}) is now replicating from Master host (${mhost}).\n\n";
	else
		failtest "There was an error configuring replication.  Things to check:\n!\n! On the slave host (${shost}) check the output of:\n! mysql> show slave status \G\n!\n! Check the mysql error log ${shost_logerror}.";
	fi
}

# Print tool header
mysql_header;

# Check mysql environment on this host (slave host).
mysql_sanitycheck;

# Dump from master
mysql_dumpmaster;

# Import into slave host
mysql_importdump;

# Create replication user, configure replication
mysql_configrepl;

# Check that the replication threads are showing good
mysql_checkrepl;

# Remove dump file
rm ${mhost_dumpfile} 2> /dev/null
