#!/usr/bin/bash

SECNUM=1
function section { echo -e "\n\\033[1;4m$SECNUM.  $1\\033[0m"; SECNUM=$((SECNUM+1)); };
function item    { echo -e "\n\\033[1m$1\\033[0m"; };

# This is the directory used by mysql when it automatically generates its certificates
CADIR="/var/lib/mysql"

usage()
{
cat 1>&2 << EOF
Usage: $0 Parameters

Parameters
   --server-id     The ID of this node (e.g. 1)                                      (required)
   --self          The internal hostanme of this node (e.g. node1.localdomain)       (required)
   --peer          The internal hostanme of the peer node (e.g. node2.localdomain)   (required)

e.g. $0 --server-id=<n> --self=<local-internal-hostname> --peer=<peer-internal-hostname>

EOF
exit 100
}

for i in "$@"; do
        case $i in
            --server-id=*)
                SERVER_ID="${i#*=}"
                shift
                ;;
            --self=*)
                SELF="${i#*=}"
                shift
                ;;
            --peer=*)
                PEER="${i#*=}"
                shift 
                ;;
            *)
               # unknown option
               echo "ERROR: Unrecognized parameter $i"
               usage  
               ;;
        esac
done

if [[ -z "$SERVER_ID" || -z "$SELF" || -z "$PEER" ]]; then
        usage
        exit 1
fi


# Make sure the config files exist
item " * Updating mysql configuration /etc/mysql/conf.d/70-replication.cnf"
cat <<-EOF > /etc/mysql/conf.d/70-replication.cnf
        [mysqld]
        bind-address          = '*'
        server-id             = ${SERVER_ID}
        report-host           = ${SELF}
        auto_increment_offset = ${SERVER_ID}
	EOF

#
# We need to restart mysqld here becuase the client will immediately pick up the ssl settings, but
# the server needs a restart first, otherwise all our grants etc will fail
#
item " * Restarting mysqld to apply configuration changes"
systemctl restart mysqld


section "Updating mysql GRANTs"
# TODO: Can we just load this hash MySQL direct? it *MUST* match the MySQL root
#       password generated in init-mysql-server
item " * Granting root privileges for replication peers"
ROOTPASS=$(ng-mk-auth-token -f /etc/sysconfig/authseed mysql:root@localhost 16)
for i in $SELF $PEER; do
	echo "   DROP USER IF EXISTS 'root'@'$i'"
	mysql -NB -e "DROP USER IF EXISTS 'root'@'$i'"

	echo "   CREATE USER 'root'@'$i' IDENTIFIED BY '$ROOTPASS' REQUIRE SSL;"
	mysql -NB -e "CREATE USER 'root'@'$i' IDENTIFIED BY '$ROOTPASS' REQUIRE SSL;"

	echo "   GRANT ALL PRIVILEGES ON *.* TO 'root'@'$i';"
	mysql -NB -e "GRANT ALL PRIVILEGES ON *.* TO 'root'@'$i';"
done

item " * Granting replication slave privileges for replication peers"
REPLPASS=$(ng-mk-auth-token -f /etc/sysconfig/authseed mysql:replicate@localhost 16)
for i in $SELF $PEER; do
	echo "   DROP USER IF EXISTS 'replicate'@'$i'"
	mysql -NB -e "DROP USER IF EXISTS 'replicate'@'$i'";

	echo "   CREATE USER 'replicate'@'$i' IDENTIFIED BY '$REPLPASS' REQUIRE x509;"
	mysql -NB -e "CREATE USER 'replicate'@'$i' IDENTIFIED BY '$REPLPASS' REQUIRE x509;"

	echo "   GRANT REPLICATION SLAVE ON *.* TO 'replicate'@'$i';"
	mysql -NB -e "GRANT REPLICATION SLAVE ON *.* TO 'replicate'@'$i';"
done

section "Configuring replication source (CHANGE REPLICATION SOURCE)"
# stop the existing replica as it running will block the change replication command
mysql -NB -e 'STOP REPLICA';

echo -e "   CHANGE REPLICATION SOURCE TO SOURCE_HOST = '${PEER}',\n" \
   "                 SOURCE_USER       = 'replicate',\n" \
   "                 SOURCE_PORT       = 3306,\n" \
   "                 SOURCE_SSL        = 1,\n" \
   "                 SOURCE_PASSWORD   = '${REPLPASS}',\n" \
   "                 SOURCE_SSL_CA     = '${CADIR}/ca.pem',\n" \
   "                 SOURCE_SSL_CERT   = '${CADIR}/server-cert.pem',\n" \
   "                 SOURCE_SSL_CIPHER = 'ECDHE-ECDSA-AES256-GCM-SHA384',\n" \
   "                 SOURCE_SSL_KEY    = '${CADIR}/server-key.pem';\n" \
| mysql -v -NB | sed -re 's/^/   /g'

# Now actually start the replication
mysql -NB -e 'START REPLICA';

