#!/usr/bin/env sh
set -eu

ROOT="$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)"
BUILD_DIR="$ROOT/build-tests"

# See bin/build: parallel agents share this tree, so test builds take turns too.
if command -v flock >/dev/null 2>&1 && [ "${OMAPRESENT_TEST_LOCKED:-}" != 1 ]; then
  mkdir -p "$BUILD_DIR"
  OMAPRESENT_TEST_LOCKED=1
  export OMAPRESENT_TEST_LOCKED
  exec flock "$BUILD_DIR/.lock" "$0" "$@"
fi

if command -v qmake6 >/dev/null 2>&1; then
  QMAKE=qmake6
else
  QMAKE=qmake
fi

status=0

# --- The application binary -------------------------------------------------
# Some suites drive the CLI (publish confirmation, argument handling), and they
# skip themselves when build/omapresent is missing -- which meant they never ran
# unless someone happened to build first. Build it here so they always do.
"$ROOT/bin/build" >/dev/null || {
  echo "bin/build failed; the CLI suites will skip" >&2
}

# --- C++ suites (tests/tst_*.cpp, one binary, see tests/testrunner.h) --------
mkdir -p "$BUILD_DIR"
(
  cd "$BUILD_DIR"
  "$QMAKE" "$ROOT/tests/tests.pro"
  make -j"$(nproc 2>/dev/null || echo 1)"
)
echo "== C++ suites =="
QT_QPA_PLATFORM=offscreen "$BUILD_DIR/tst_omapresent" || status=$?

# --- Renderer suites (tests/renderer/*.test.mjs, pure ES modules) -----------
if command -v node >/dev/null 2>&1; then
  if ls "$ROOT"/tests/renderer/*.test.mjs >/dev/null 2>&1; then
    echo "== renderer suites =="
    (cd "$ROOT" && node --test tests/renderer/) || status=$?
  fi
else
  echo "node not found; skipping renderer suites" >&2
fi

exit "$status"
