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

cd "$(dirname "$0")"

if [ -f local-tools/env.sh ]; then
  . ./local-tools/env.sh
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
if [ -z "$cases_arg" ]; then
  cases_arg="--cases=correct_scalars_ops,correct_control_flow,correct_functions_scope,correct_arrays,correct_strings_builtins,correct_native_string_concat_assign,correct_include_literal,correct_embed_builtins,correct_runtime_builtins,correct_regex_builtins,correct_files_process_builtins,correct_classes_static,correct_modern_control,correct_globals_references,tool_php_slots,tool_pw_repo_helper,real_pylon_loopback,real_valaphp_libpwcommon,real_valaphp_benchmark,pwphpbytecode_library,pwcomposer_library,php2vala_embed_pwphpbytecode_lib"
  build_case_ids="--case-ids=${cases_arg#--cases=}"
fi

engine_build_dir="build/correctness-engine-build"
echo "Preparing selected correctness 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/correctness \
  --repeats=1 \
  --warmups=0 \
  --verify-correctness=1 \
  ${cases_arg} \
  "$@"
