#!/usr/bin/env bash
set -euo pipefail

project_root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
build_dir="${project_root}/build/cmake"
export WINEPREFIX="${WINEPREFIX:-${HOME}/.wine}"
original_args=("$@")
jobs=8
list_only=0
visible=0
name_patterns=()

usage() {
  cat <<'EOF'
Usage: ./run [--list] [--visible] [-j N] [FILTER ...]

Runs CTest under one Xvfb server. --visible uses the current display. Tests use
8 workers by default. Positional arguments are test-name regexes.
EOF
}

while (($#)); do
  case "$1" in
    --list)
      list_only=1
      shift
      ;;
    --visible)
      visible=1
      shift
      ;;
    -j|--jobs)
      [[ $# -ge 2 ]] || { echo "missing value for $1" >&2; exit 2; }
      jobs="$2"
      shift 2
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    --)
      shift
      name_patterns+=("$@")
      break
      ;;
    -* )
      echo "unknown option: $1" >&2
      usage >&2
      exit 2
      ;;
    *)
      name_patterns+=("$1")
      shift
      ;;
  esac
done

[[ "$jobs" =~ ^[1-9][0-9]*$ ]] || { echo "invalid job count: $jobs" >&2; exit 2; }
: "${LLVM_BUILD:?set LLVM_BUILD to the C166 LLVM build directory}"
export LLVM_BUILD="$(readlink -m -- "${LLVM_BUILD}")"

if ((list_only)); then
  cmake -S "$project_root" -B "$build_dir" -DC166_TEST_JOBS="$jobs"
  ctest_args=(--test-dir "$build_dir" --output-on-failure)
  if ((${#name_patterns[@]})); then
    regex="$(IFS='|'; echo "${name_patterns[*]}")"
    ctest_args+=(-R "$regex")
  fi
  exec ctest "${ctest_args[@]}" -N
fi

if ((!visible)) && [[ "${C166_HEADLESS_X_ACTIVE:-0}" != 1 ]]; then
  exec "${project_root}/tools/with-headless-x" "$0" "${original_args[@]}"
fi

if [[ "${C166_WINE_SERVER_ACTIVE:-0}" != 1 ]]; then
  exec "${project_root}/tools/with-wine-server" \
    env C166_WINE_SERVER_ACTIVE=1 "$0" "${original_args[@]}"
fi

cmake -S "$project_root" -B "$build_dir" -DC166_TEST_JOBS="$jobs"

ctest_args=(--test-dir "$build_dir" --output-on-failure)
if ((${#name_patterns[@]})); then
  regex="$(IFS='|'; echo "${name_patterns[*]}")"
  ctest_args+=(-R "$regex")
fi

if ((${#name_patterns[@]} == 0)); then
  cmake --build "$build_dir" --target c166-tests-build --parallel "$jobs"
  ctest_args+=(-E '^build\.' -FA '^fixture-')
fi

if ((visible)); then
  export C166_TEST_VISIBLE=1
fi
exec ctest "${ctest_args[@]}" -j "$jobs"
