#!/bin/sh
# Bootstrap cast02 or cast03 as GTID replica of cast01.
set -eu
set -o pipefail
SHARED=/shared/cluster
CREDS="$SHARED/credentials.txt"
[ -f "$SHARED/cluster.env" ] && . "$SHARED/cluster.env"
HOST="$(hostname -s)"
case "$HOST" in
  cast02) SERVER_ID=2 ;;
  cast03) SERVER_ID=3 ;;
  *) echo "run on cast02 or cast03"; exit 1 ;;
esac

REPL_PASS="$(awk '/^\[mariadb_replication\]/{f=1;next} /^\[/{f=0} f&&/^password=/{print substr($0,10); exit}' "$CREDS")"
REPL_USER="$(awk '/^\[mariadb_replication\]/{f=1;next} /^\[/{f=0} f&&/^user=/{print substr($0,6); exit}' "$CREDS")"
APP_PASS="$(awk '/^\[mariadb_app\]/{f=1;next} /^\[/{f=0} f&&/^password=/{print substr($0,10); exit}' "$CREDS")"
APP_USER="$(awk '/^\[mariadb_app\]/{f=1;next} /^\[/{f=0} f&&/^user=/{print substr($0,6); exit}' "$CREDS")"

grep -q '^skip-networking' /etc/my.cnf.d/mariadb-server.cnf && \
  sed -i 's/^skip-networking/#skip-networking/' /etc/my.cnf.d/mariadb-server.cnf

apk add --no-cache mariadb
install -D -m 644 "$SHARED/mariadb/replica.cnf" /etc/my.cnf.d/lab-cluster-replica.cnf
grep -q '^server-id=' /etc/my.cnf.d/lab-cluster-replica.cnf && \
  sed -i "s/^server-id=.*/server-id=${SERVER_ID}/" /etc/my.cnf.d/lab-cluster-replica.cnf || \
  echo "server-id=${SERVER_ID}" >> /etc/my.cnf.d/lab-cluster-replica.cnf

rc-service mariadb stop 2>/dev/null || true
rm -rf /var/lib/mysql/*
/etc/init.d/mariadb setup

rc-update add mariadb default
rc-service mariadb restart
sleep 2

echo "=== app DB sync from cast01 (skip mysql.* — avoids help_topic dump failures) ==="
mariadb-dump --skip-ssl -h cast01 -u "${REPL_USER}" -p"${REPL_PASS}" \
  --databases androidcast_crashes url_shortener \
  --single-transaction --gtid --routines --events \
  | mariadb -u root

GTID_POS="$(mariadb --skip-ssl -h cast01 -u "${REPL_USER}" -p"${REPL_PASS}" -N -e 'SELECT @@gtid_current_pos')"
[ -n "$GTID_POS" ] || { echo "FAIL: could not read gtid from cast01"; exit 1; }
mariadb -u root -e "SET GLOBAL gtid_slave_pos='${GTID_POS}'"
echo "gtid_slave_pos set to: ${GTID_POS}"

mariadb -u root <<SQL
CREATE USER IF NOT EXISTS '${APP_USER}'@'10.7.16.%' IDENTIFIED BY '${APP_PASS}';
CREATE USER IF NOT EXISTS '${APP_USER}'@'localhost' IDENTIFIED BY '${APP_PASS}';
GRANT ALL PRIVILEGES ON androidcast_crashes.* TO '${APP_USER}'@'10.7.16.%';
GRANT ALL PRIVILEGES ON androidcast_crashes.* TO '${APP_USER}'@'localhost';
GRANT ALL PRIVILEGES ON url_shortener.* TO '${APP_USER}'@'10.7.16.%';
GRANT ALL PRIVILEGES ON url_shortener.* TO '${APP_USER}'@'localhost';
FLUSH PRIVILEGES;
CHANGE MASTER TO
  MASTER_HOST='cast01',
  MASTER_USER='${REPL_USER}',
  MASTER_PASSWORD='${REPL_PASS}',
  MASTER_USE_GTID=slave_pos;
START REPLICA;
SQL

sleep 3
mariadb -u root -e "SHOW REPLICA STATUS\G" | grep -E 'Slave_IO_Running|Slave_SQL_Running|Last_Error|Last_SQL_Error|Seconds_Behind_Master'
mariadb -u root -e "SELECT table_schema, COUNT(*) AS tables FROM information_schema.tables WHERE table_schema IN ('androidcast_crashes','url_shortener') GROUP BY table_schema;"
URL_N="$(mariadb -u root -N -e 'SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='"'"'url_shortener'"'"'')"
CRASH_N="$(mariadb -u root -N -e 'SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='"'"'androidcast_crashes'"'"'')"
EXP_CRASH="${EXPECTED_CRASHES_TABLES:-16}"
EXP_URL="${EXPECTED_URL_SHORTENER_TABLES:-4}"
[ "$CRASH_N" = "$EXP_CRASH" ] && [ "$URL_N" = "$EXP_URL" ] || { echo "FAIL: expected ${EXP_CRASH}+${EXP_URL} tables, got crashes=$CRASH_N url=$URL_N"; exit 1; }
mariadb -u root -e "SHOW REPLICA STATUS\G" | grep -E 'Slave_SQL_Running: Yes' >/dev/null || { echo "FAIL: SQL thread not running"; mariadb -u root -e "SHOW REPLICA STATUS\G" | grep -E 'Last_SQL_Error'; exit 1; }
echo "replica_ok $HOST server_id=$SERVER_ID"
