#!/bin/bash
#
# This is an entrypoint that runs the MySQL server in the 'slave' mode.
#

export_vars=$(cgroup-limits); export $export_vars
source ${CONTAINER_SCRIPTS_PATH}/common.sh
set -eu
if [[ -v DEBUG_IGNORE_SCRIPT_FAILURES ]]; then
  set +e
fi

export_setting_variables

log_volume_info $MYSQL_DATADIR

export MYSQL_RUNNING_AS_SLAVE=1

# Generate the unique 'server-id' for this master
export MYSQL_SERVER_ID=$(server_id)
log_info "The 'slave' server-id is ${MYSQL_SERVER_ID}"

# pre-init files
process_extending_files ${APP_DATA}/mysql-pre-init/ ${CONTAINER_SCRIPTS_PATH}/pre-init/

if [ ! -e "${MYSQL_DATADIR}/mysql" ]; then
  # Initialize MySQL database and wait for the MySQL master to accept
  # connections.
  initialize_database "$@"
  wait_for_mysql_master

  mysql $mysql_flags <<EOSQL
CHANGE MASTER TO MASTER_HOST='${MYSQL_MASTER_SERVICE_NAME}',MASTER_USER='${MYSQL_MASTER_USER}', MASTER_PASSWORD='${MYSQL_MASTER_PASSWORD}', MASTER_AUTO_POSITION = 1;
EOSQL

  # init files
  process_extending_files ${APP_DATA}/mysql-init/ ${CONTAINER_SCRIPTS_PATH}/init/

  # Restart the MySQL server with public IP bindings
  shutdown_local_mysql
fi

unset_env_vars
log_volume_info $MYSQL_DATADIR
log_info 'Running final exec -- Only MySQL server logs after this point'
exec ${MYSQL_PREFIX}/libexec/mysqld --defaults-file=$MYSQL_DEFAULTS_FILE \
  --report-host=$(hostname -I) "$@" 2>&1
