#!/bin/sh
# Load project schemas on cast01 primary only.
set -eu
SHARED=/shared/cluster/sql
[ "$(hostname -s)" = cast01 ] || { echo "run on cast01 only"; exit 1; }

apply() {
  f="$1"
  [ -f "$f" ] || { echo "missing $f"; exit 1; }
  echo "==> $f"
  mariadb -u root < "$f"
}

apply_db() {
  db="$1"
  f="$2"
  echo "==> $db < $f"
  mariadb -u root "$db" < "$f"
}

apply "$SHARED/crashes/schema.mariadb.sql"

# Migrations after base schema (003 is for legacy; base schema already includes tickets)
for m in \
  004_ticket_workflow.sql \
  005_ticket_attachments.sql \
  006_graph_sessions.sql \
  007_remote_access.sql \
  008_graph_sessions_indexes.sql \
  008_auth_email_2fa.sql \
  009_rssh_sessions.sql
do
  apply_db androidcast_crashes "$SHARED/crashes/migrations/$m"
done

apply "$SHARED/url_shortener/schema.mariadb.sql"

mariadb -u root -e "SHOW DATABASES; SELECT COUNT(*) AS crash_tables FROM information_schema.tables WHERE table_schema='androidcast_crashes'; SELECT COUNT(*) AS url_tables FROM information_schema.tables WHERE table_schema='url_shortener';"
echo "schemas_loaded_ok"
