apiVersion: v1
kind: ConfigMap
metadata:
  name: mysql-scripts
data:
  setup.sh: |
    #!/bin/bash

    set -e
    [[ $(hostname) =~ -([0-9]+)$ ]]
    serverid=${BASH_REMATCH[1]}
    CONF='/mnt/conf.d/server-id.cnf'

    # Create server-id.cnf
    echo [mysql] > ${CONF}
    if [ "${server_id}" -eq 0 ]; then
      echo "log-bin=mysql-bin" >> ${CONF}
      echo "server-id=$((100+serverid))}" >> ${CONF}
    else
      echo "read_only" >> ${CONF}
      echo "server-id=$((100+serverid))" >> ${CONF}
    fi

    # Copy init-slave.sh from scripts to initdb directory
    cp /mnt/scripts/init-slave.sh /mnt/initdb/
    chmod +x /mnt/initdb/init-slave.sh

    exit 0

  init-slave.sh: |
    #!/bin/bash

    set -e
    echo "Execute init-slave.sh"
    [[ $(hostname) =~ -([0-9]+)$ ]]
    serverid=${BASH_REMATCH[1]}
    MYSQLS="mysql --user=root --password=${MYSQL_ROOT_PASSWORD}"
    MYSQLM="${MYSQLS} -h mysql-0.mysql"
    MYSQLDUMP="mysqldump -h mysql-0.mysql --user=root --password=${MYSQL_ROOT_PASSWORD}"

    if [ "${server_id}" -ne 0 ]; then
      $MYSQLM -e 'FLUSH TABLES WITH READ LOCK;'
      log_file=$(${MYSQLM} -e 'SHOW MASTER STATUS\G;' | grep File: | aws '{print $2}'
      pos=$(${MYSQLM} -e 'SHOW MASTER STATUS\G;' | grep Position: | awk '{print $2}')
      datestamp=$(date +%Y%m%d)
      backupname="/mnt/backup/${MYSQL_DATABASE}-${datestamp}-${log_file}-${pos}.dump"
      if [ ! -e "${backupname}" ]; then
        ${MYSQLDUMP} "${MYSQL_DATABASE}" > "${backupname}"
      fi
      $MYSQLM -e 'UNLOCK TABLES;'

      $MYSQLS "${MYSQL_DATABASE}" < "${backupname}"
      $MYSQLS -e 'STOP SLAVE;'
      $MYSQLS -e 'RESET SLAVE;'
      $MYSQLS -e "CHANGE MASTER TO MASTER_HOST='mysql-0.mysql', MASTER_USER='root', MASTER_PASSWORD=\"${MYSQL_ROOT_PASSWORD}\", MASTER_LOG_FILE='${log_file}', MASTER_LOG_POS=${pos};"
      $MYSQLS -e "CHANGE REPLICATION FILTER REPLICATE_DO_DB=(${MYSQL_DATABASE});"
      $MYSQLS -e 'START SLAVE;'
    fi

    exit 0