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

cd "$(dirname "$0")"

if [ -f local-tools/env.sh ]; then
  . ./local-tools/env.sh
fi

if [ ! -d build ]; then
  meson setup build --buildtype=release
fi

if [ ! -f build/generated/cases/correct_scalars_ops.php ]; then
  echo "Generated cases missing; running Meson case generation first." >&2
  meson compile -C build cases.stamp
fi

cases_arg=""
build_case_ids=""
build_engine_ids=""
prev=""
for arg in "$@"; do
  if [ "$prev" = "--cases" ]; then
    cases_arg="--cases=$arg"
    build_case_ids="--case-ids=$arg"
    prev=""
    continue
  fi
  if [ "$prev" = "--engines" ]; then
    build_engine_ids="--engine-ids=$arg"
    prev=""
    continue
  fi
  case "$arg" in
    --cases=*)
      cases_arg="$arg"
      build_case_ids="--case-ids=${arg#--cases=}"
      ;;
    --cases)
      prev="--cases"
      ;;
    --engines=*)
      build_engine_ids="--engine-ids=${arg#--engines=}"
      ;;
    --engines)
      prev="--engines"
      ;;
  esac
done

engine_build_dir="build/performance-engine-build"
echo "Preparing performance engine artifacts in ${engine_build_dir}." >&2
php tools/build_engines.php \
  --cases build/generated/cases \
  --build-dir "$engine_build_dir" \
  --php-slot 8.3 \
  --abiver 3 \
  ${build_case_ids} \
  ${build_engine_ids}

php tools/run_benchmarks.php \
  --cases-dir build/generated/cases \
  --engine-commands "$engine_build_dir/engine-commands.json" \
  --results-dir results/performance \
  --verify-correctness=0 \
  --verify-optimizer-gates=1 \
  ${cases_arg} \
  "$@"
