#!/bin/sh
# Quick health check for cast cluster.
set -eu
HOST="$(hostname -s)"
FAIL=0
echo "=== $HOST ==="
mount | grep ' /shared ' || { echo "WARN: /shared not mounted"; FAIL=1; }
curl -sS -o /dev/null -w "nginx=%{http_code}\n" http://127.0.0.1/ || true
php83 -v | head -1

case "$HOST" in
  cast01)
    mariadb -u root -e "SELECT @@server_id AS server_id, @@read_only AS read_only, @@gtid_current_pos AS gtid;"
    mariadb -u androidcast -pcast-cluster-dev -h127.0.0.1 -e \
      "SELECT table_schema, COUNT(*) AS tables FROM information_schema.tables WHERE table_schema IN ('androidcast_crashes','url_shortener') GROUP BY table_schema;"
    ;;
  cast02|cast03)
    mariadb -u root -e "SELECT @@server_id AS server_id, @@read_only AS read_only;" 2>/dev/null || { echo "mariadb not running"; FAIL=1; }
    RS="$(mariadb -u root -e 'SHOW REPLICA STATUS\G' 2>/dev/null || true)"
    echo "$RS" | grep -E 'Master_Host|Slave_IO_Running|Slave_SQL_Running|Seconds_Behind_Master|Last_SQL_Error' || true
    echo "$RS" | grep -E 'Slave_IO_Running: Yes' >/dev/null || { echo "FAIL: IO thread not running"; FAIL=1; }
    echo "$RS" | grep -E 'Slave_SQL_Running: Yes' >/dev/null || { echo "FAIL: SQL thread not running"; FAIL=1; }
    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;"
    mariadb -u androidcast -pcast-cluster-dev -h127.0.0.1 -e "SELECT 1 AS local_read_ok;" 2>/dev/null || echo "WARN: local app user read failed"
    ;;
esac

if [ "$FAIL" -eq 0 ]; then
  echo OK
else
  echo FAIL
  exit 1
fi
