#!/bin/sh
# Fresh MariaDB setup for crash reporter (run on BE as root or with mysql admin).
# Usage:
#   ./scripts/init-mariadb.sh
#   CRASH_DB_PASS='secret' ./scripts/init-mariadb.sh
set -eu

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
SCHEMA="$ROOT/sql/schema.mariadb.sql"
MIG002="$ROOT/sql/migrations/002_reports_company_columns.sql"
MIG003="$ROOT/sql/migrations/003_tickets.sql"
DB_NAME="${CRASH_DB_NAME:-androidcast_crashes}"
DB_USER="${CRASH_DB_USER:-androidcast}"
DB_PASS="${CRASH_DB_PASS:-}"

if [ ! -f "$SCHEMA" ]; then
  echo "Missing $SCHEMA" >&2
  exit 1
fi

echo "Applying schema from $SCHEMA ..."
mysql -u root -p < "$SCHEMA"

if [ -f "$MIG002" ]; then
  echo "Applying RBAC report columns (002) ..."
  mysql -u root -p "$DB_NAME" < "$MIG002"
fi

if [ -f "$MIG003" ]; then
  echo "Applying tickets table (003) ..."
  mysql -u root -p "$DB_NAME" < "$MIG003"
fi

if [ -n "$DB_PASS" ]; then
  echo "Creating app user ${DB_USER}@localhost and @127.0.0.1 ..."
  mysql -u root -p <<EOF
CREATE USER IF NOT EXISTS '${DB_USER}'@'localhost' IDENTIFIED BY '${DB_PASS}';
CREATE USER IF NOT EXISTS '${DB_USER}'@'127.0.0.1' IDENTIFIED BY '${DB_PASS}';
GRANT SELECT, INSERT, UPDATE, DELETE ON ${DB_NAME}.* TO '${DB_USER}'@'localhost';
GRANT SELECT, INSERT, UPDATE, DELETE ON ${DB_NAME}.* TO '${DB_USER}'@'127.0.0.1';
FLUSH PRIVILEGES;
EOF
else
  echo "Skip app user: set CRASH_DB_PASS to create '${DB_USER}'@localhost and @127.0.0.1"
fi

echo "Done. Set config.php: db.driver = mysql, db.mysql.* then restart php-fpm."
