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

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

ITER="${1:-200}"
BATCH="${2:-10}"
SAFE_TOTAL="${FLOWLOG_BENCH_BIGINT_MAX_TOTAL:-3500}"

total_ops=$((ITER * BATCH))

echo "bench: building flowlog..." >&2
make -C "$ROOT" -s >/dev/null

PROG="$ROOT/bench/bigint_arith.pl"

run_engine() {
  local engine="$1"
  local iter="$ITER"
  local batch="$BATCH"
  if [[ "$engine" != "wamvm" && "$total_ops" -gt "$SAFE_TOTAL" ]]; then
    local max_iter=$((SAFE_TOTAL / BATCH))
    if (( max_iter < 1 )); then
      max_iter=1
      batch="$SAFE_TOTAL"
    fi
    iter="$max_iter"
    echo "bench: $engine cap (iter*batch=$total_ops > $SAFE_TOTAL); using iter=$iter batch=$batch" >&2
  fi
  local env_prefix=()
  if [[ "$engine" == "wamvm" ]]; then
    env_prefix=(env FLOWLOG_WAMVM_REQUIRE_VM=1)
  fi
  echo "--- flowlog (engine=$engine) ---" >&2
  /usr/bin/time -p \
    "${env_prefix[@]}" "$ROOT/flowlog" --threads 1 --engine "$engine" "$PROG" \
    -g "bench($iter, $batch), halt." 2>&1
}

echo "bench: bigint_arith iter=$ITER batch=$BATCH" >&2
echo "bench: program=$PROG" >&2

run_engine interp
run_engine wam
run_engine wamvm
