#!/bin/bash
set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

usage() {
  echo "Usage:"
  echo "  $0 --host HOST --port PORT [--db DATABASE] [--jar PATH_TO_JDBC_JAR] [--classdir DIR]"
  echo ""
  echo "  --db        database to use/create (default: test)"
  echo "  --jar       path to the MariaDB Connector/J jar (default: auto-detect *.jar in script dir)"
  echo "  --classdir  directory containing compiled MDEV40911Repro.class (default: script dir)"
  echo ""
  echo "Example:"
  echo "  $0 --host 127.0.0.1 --port 13306 --jar /path/to/mariadb-java-client-3.5.10.jar"
  exit 1
}

HOST=""
PORT=""
DB="test"
JAR=""
CLASSDIR="$SCRIPT_DIR"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --host)     HOST="$2"; shift 2 ;;
    --port)     PORT="$2"; shift 2 ;;
    --db)       DB="$2"; shift 2 ;;
    --jar)      JAR="$2"; shift 2 ;;
    --classdir) CLASSDIR="$2"; shift 2 ;;
    -h|--help)  usage ;;
    *) echo "Unknown argument: $1"; usage ;;
  esac
done

[[ -n "$HOST" && -n "$PORT" ]] || usage

if [[ -z "$JAR" ]]; then
  JAR="$(find "$SCRIPT_DIR" -maxdepth 1 -iname 'mariadb-java-client*.jar' | head -1)"
fi

if [[ -z "$JAR" || ! -f "$JAR" ]]; then
  echo "Error: MariaDB Connector/J jar not found. Pass its path with --jar."
  exit 1
fi

if [[ ! -f "$CLASSDIR/MDEV40911Repro.class" ]]; then
  echo "Error: MDEV40911Repro.class not found in $CLASSDIR."
  echo "Compile it first: javac -cp \"$JAR\" MDEV40911Repro.java"
  exit 1
fi

if ! mysqladmin --no-defaults -h"$HOST" -P"$PORT" -uroot ping >/dev/null 2>&1; then
  echo "Error: no server responding on $HOST:$PORT"
  exit 1
fi

CLIENT="$(command -v mariadb || command -v mysql || true)"
if [[ -z "$CLIENT" ]]; then
  echo "Error: no 'mariadb' or 'mysql' client binary found in PATH."
  exit 1
fi

echo "Ensuring database '$DB' exists on $HOST:$PORT..."
"$CLIENT" --no-defaults -h"$HOST" -P"$PORT" -uroot -e "CREATE DATABASE IF NOT EXISTS \`$DB\`;"

echo "Using $HOST:$PORT  db=$DB  jar=$JAR"
java -cp "$CLASSDIR:$JAR" MDEV40911Repro "$HOST" "$PORT" "$DB"
