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

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

N="${1:-4}"
PROG="${FLOWLOG_BENCH_MAGIC_SQUARE_FILE:-$ROOT/bench/magic_square.pl}"

if [[ ! -x "$ROOT/flowlog" ]]; then
  echo "bench: building flowlog..." >&2
  (cd "$ROOT" && make -s)
fi

threads=""
if command -v nproc >/dev/null 2>&1; then
  threads="$(nproc)"
elif command -v sysctl >/dev/null 2>&1; then
  threads="$(sysctl -n hw.ncpu 2>/dev/null || true)"
fi
threads="${threads:-1}"

echo "bench: magic_square N=$N" >&2
echo "bench: threads=$threads" >&2
echo "bench: program=$PROG" >&2

echo "--- flowlog (engine=wam parallel_profile=fast) ---" >&2
/usr/bin/time -p \
  "$ROOT/flowlog" --threads "$threads" --engine wam --parallel-profile fast "$PROG" \
  -g "magic_square_len($N, Count), write(Count), nl, halt." 2>&1
echo "--- flowlog (engine=wamvm parallel_profile=fast) ---" >&2
/usr/bin/time -p \
  "$ROOT/flowlog" --threads "$threads" --engine wamvm --parallel-profile fast "$PROG" \
  -g "magic_square_len($N, Count), write(Count), nl, halt." 2>&1
echo "--- flowlog (engine=tree parallel_profile=fast) ---" >&2
/usr/bin/time -p \
  "$ROOT/flowlog" --threads "$threads" --engine tree --parallel-profile fast "$PROG" \
  -g "magic_square_len($N, Count), write(Count), nl, halt." 2>&1
echo "--- flowlog (engine=wam parallel_profile=iso) ---" >&2
/usr/bin/time -p \
  "$ROOT/flowlog" --threads "$threads" --engine wam --parallel-profile iso "$PROG" \
  -g "magic_square_len($N, Count), write(Count), nl, halt." 2>&1
echo "--- flowlog (engine=wamvm parallel_profile=iso) ---" >&2
/usr/bin/time -p \
  "$ROOT/flowlog" --threads "$threads" --engine wamvm --parallel-profile iso "$PROG" \
  -g "magic_square_len($N, Count), write(Count), nl, halt." 2>&1
echo "--- flowlog (engine=tree parallel_profile=iso) ---" >&2
/usr/bin/time -p \
  "$ROOT/flowlog" --threads "$threads" --engine tree --parallel-profile iso "$PROG" \
  -g "magic_square_len($N, Count), write(Count), nl, halt." 2>&1

if command -v tpl >/dev/null 2>&1; then
  echo "--- tpl ---" >&2
  /usr/bin/time -p \
    tpl -q -f "$PROG" \
    -g "magic_square_len($N, Count), write(Count), nl, halt." 2>&1
else
  echo "bench: tpl not found; skipping" >&2
fi

if command -v scryer-prolog >/dev/null 2>&1; then
  echo "--- scryer-prolog ---" >&2
  /usr/bin/time -p \
    scryer-prolog -f "$PROG" \
    -g "use_module(library(lists)), magic_square_len($N, Count), write(Count), nl, halt." 2>&1
else
  echo "bench: scryer-prolog not found; skipping" >&2
fi
