#!/bin/bash
# sqlmorph — MySQL stored-routine install script.  Built by Oninit LLC.
#
# Installs every *.sql file in the current directory (or BUNDLE_DIR) into
# the target MySQL database via the mysql client. Each .sql file is piped
# in via stdin so the bundle's `DELIMITER //` ... `DELIMITER ;` pragmas
# take effect (the mysql client's `-e` flag does NOT honour DELIMITER).
#
# The emitted .sql files use `DROP FUNCTION/PROCEDURE IF EXISTS` before
# the CREATE, so reruns are safe.
#
# Usage:
#   ./install.mysql.sh -D <db> -h <host> -u <user> [-p <password>]
#   ./install.mysql.sh -D mydb -h localhost -u root
#
# Or via env:
#   MYSQL_DB=mydb MYSQL_HOST=localhost MYSQL_USER=root \
#       MYSQL_PWD=secret ./install.mysql.sh
#
# Defaults: -h localhost  -u root  -D sqlmorph_test
# Password is optional — if omitted, mysql tries socket auth or empty
# password per local config.
set -euo pipefail

DB="${MYSQL_DB:-sqlmorph_test}"
HOST="${MYSQL_HOST:-localhost}"
USER="${MYSQL_USER:-root}"
PWD="${MYSQL_PWD:-}"
BUNDLE_DIR="${BUNDLE_DIR:-.}"

while [[ $# -gt 0 ]]; do
    case "$1" in
        -D) DB="$2"; shift 2 ;;
        -h) HOST="$2"; shift 2 ;;
        -u) USER="$2"; shift 2 ;;
        -p) PWD="$2"; shift 2 ;;
        --help) sed -n '2,21p' "$0" | sed 's/^# \?//' ; exit 0 ;;
        *) echo "unknown arg: $1" >&2 ; exit 2 ;;
    esac
done

if ! command -v mysql >/dev/null 2>&1; then
    echo "mysql client not on PATH." >&2
    exit 2
fi

# Build mysql connection args. Use MYSQL_PWD env var so the password
# never appears in `ps`.
mysql_args=("-h" "$HOST" "-u" "$USER" "-D" "$DB")
if [[ -n "$PWD" ]]; then
    export MYSQL_PWD="$PWD"
fi

shopt -s nullglob
ordered=("$BUNDLE_DIR"/*.sql)

if [[ ${#ordered[@]} -eq 0 ]]; then
    echo "no *.sql files found in $BUNDLE_DIR" >&2
    exit 2
fi

echo "==> sqlmorph MySQL install (db=$DB, host=$HOST, user=$USER)"
fail=0
for f in "${ordered[@]}"; do
    echo "    mysql < $f"
    if ! mysql "${mysql_args[@]}" <"$f"; then
        echo "    FAILED: $f" >&2
        fail=1
    fi
done
echo "==> $( [ $fail -eq 0 ] && echo 'ok' || echo 'errors above' )"
exit $fail
