#!/bin/bash

# This script connects to two MySQL servers using the docker mariadb image as a client
# It then makes the slave_addr server a slave of the master_addr server
# It doesn't copy any data, so don't expect this to work with existing databases :)

USAGE="./bin/mysql_setup.sh master_addr slave_addr password"
PROJECT="sqlsidecar"

if [ -z "$1" ] || [ -z "$2" ] || [ -z "$3" ]; then
  echo $USAGE
  exit 1
fi
MASTER_ADDR="$1"
SLAVE_ADDR="$2"
PASSWORD="$3"

RETRIES=20
RETRY_DELAY=3

START_TIME=$(date +%s)
function waitForMySQL {
  MYSQL_TEST=`curl -m2 -s $1`
  if [ $? -eq 0 ]; then
    echo "MySQL Ready - Took $(($(date +%s) - $START_TIME)) seconds to boot"
  else
    RETRIES=$(($RETRIES-1))
    if [ $RETRIES -eq 0 ]; then
      echo "MySQL isn't running..."
      exit 1
    else
      echo "MySQL not up! Retries left: $RETRIES. Waiting $RETRY_DELAY seconds."
      sleep $RETRY_DELAY
      waitForMySQL "$1"
    fi
  fi
}
# so we dont need mysql-client locally...
function bashcmd {
  docker run \
    --network ${PROJECT}_default \
    --link ${PROJECT}_mysql_1:master \
    --link ${PROJECT}_mysql_slave_1:slave \
    --entrypoint bash \
    -it mariadb \
    -c "$1"
}
function mysqlcmd {
  bashcmd "mysql -h $1 -u root --password=${PASSWORD} -e \"$2\""
}

START_TIME=$(date +%s)
echo "Waiting for Master to start..."
waitForMySQL "$MASTER_ADDR"

START_TIME=$(date +%s)
echo "Waiting for Slave to start..."
waitForMySQL "$SLAVE_ADDR"

MASTER_STATUS=$(mysqlcmd master "\
  CREATE USER 'repl'@'%' IDENTIFIED BY '${PASSWORD}'; \
  GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%';\
  SHOW MASTER STATUS\G")

MASTER_POSITION=$(echo "$MASTER_STATUS" | fgrep "Position:" | awk '{print $2}' | tr -d '\r')
MASTER_FILE=$(echo "$MASTER_STATUS" | fgrep "File:" | awk '{print $2}' | tr -d '\r')

if [ -z $MASTER_POSITION ] || [ -z $MASTER_FILE ]; then
  echo "Failed to determine master position or logfile - exiting"
  exit 1
fi

mysqlcmd slave "SET GLOBAL read_only = ON;"
mysqlcmd slave "CHANGE MASTER TO MASTER_HOST='master', MASTER_USER='repl', MASTER_PASSWORD='${PASSWORD}', MASTER_LOG_FILE='${MASTER_FILE}', MASTER_LOG_POS=${MASTER_POSITION};" | fgrep "ERROR"
if [ $? -eq 0 ]; then
  echo "MySQL Slave failed to setup replication... Failing out"
  exit 1
fi

mysqlcmd slave "START SLAVE;"
mysqlcmd slave "GRANT SELECT ON ${PROJECT}.* TO 'reader'@'%' IDENTIFIED BY '${PASSWORD}';"

mysqlcmd master "\
  GRANT ALL ON ${PROJECT}.* TO 'writer'@'%' IDENTIFIED BY '${PASSWORD}';
"

echo "MySQL setup complete "
