#!/usr/bin/env bash
#
# Prepares a ready-to-import database for a standalone install, for hosting
# where you can't run `php artisan` on the server (no SSH / Terminal).
#
#   scripts/standalone/export-database.sh <scratch-db-name> [output.sql] [-- school:install options]
#
# Runs every migration plus `php artisan school:install` (it will ask for the
# institution name, type and admin login) against a NEW, empty local MySQL
# database, then dumps it to a .sql file you import in cPanel → phpMyAdmin.
# Uses DB_HOST / DB_PORT / DB_USERNAME / DB_PASSWORD from your local .env
# unless they are set in the environment. Refuses to touch a database that
# already exists, so it can never wipe your dev data.

set -euo pipefail

ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
DB="${1:?usage: $0 <scratch-db-name> [output.sql] [-- school:install options]}"
shift
OUT="$ROOT/dist/$DB.sql"
if [ $# -gt 0 ] && [ "$1" != "--" ]; then OUT="$1"; shift; fi
[ "${1:-}" = "--" ] && shift

env_value() { grep -E "^$1=" "$ROOT/.env" 2>/dev/null | tail -1 | cut -d= -f2- | tr -d '"'; }
HOST="${DB_HOST:-$(env_value DB_HOST)}"; HOST="${HOST:-127.0.0.1}"
PORT="${DB_PORT:-$(env_value DB_PORT)}"; PORT="${PORT:-3306}"
DBUSER="${DB_USERNAME:-$(env_value DB_USERNAME)}"; DBUSER="${DBUSER:-root}"
PASS="${DB_PASSWORD:-$(env_value DB_PASSWORD)}"

MYSQL_ARGS=(-h"$HOST" -P"$PORT" -u"$DBUSER")
[ -n "$PASS" ] && MYSQL_ARGS+=(-p"$PASS")

if mysql "${MYSQL_ARGS[@]}" -e "USE \`$DB\`" 2>/dev/null; then
    echo "Database '$DB' already exists — pick a new name. Nothing was changed." >&2
    exit 1
fi

echo "→ Creating scratch database '$DB'"
mysql "${MYSQL_ARGS[@]}" -e "CREATE DATABASE \`$DB\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"

export APP_MODE=standalone DB_CONNECTION=mysql DB_HOST="$HOST" DB_PORT="$PORT" \
       DB_DATABASE="$DB" DB_USERNAME="$DBUSER" DB_PASSWORD="$PASS"

echo "→ Running migrations (takes a few minutes)"
(cd "$ROOT" && php artisan migrate --force)

echo "→ Installing the institution"
(cd "$ROOT" && php artisan school:install "$@")

mkdir -p "$(dirname "$OUT")"
echo "→ Dumping to $OUT"
# Shared-hosting MySQL users can't set GTID_PURGED / SQL_LOG_BIN (needs SUPER),
# so a dump containing them fails to import in phpMyAdmin. MariaDB's mysqldump
# doesn't know the flag (and never writes GTIDs), so only pass it when supported.
DUMP_ARGS=(--single-transaction --no-tablespaces --skip-triggers)
mysqldump --help 2>/dev/null | grep -q -- '--set-gtid-purged' && DUMP_ARGS+=(--set-gtid-purged=OFF)
mysqldump "${MYSQL_ARGS[@]}" "${DUMP_ARGS[@]}" "$DB" > "$OUT"

echo
echo "Done: $OUT"
echo "Import it in cPanel → phpMyAdmin. The scratch database '$DB' was left in place;"
echo "drop it when you no longer need it:  DROP DATABASE \`$DB\`;"
