#!/usr/bin/env bash
# run_pgbench.sh <db> <runs> <seconds> — interleaves the three modes run by run.
set -euo pipefail
DB=$1; RUNS=${2:-5}; SECS=${3:-20}; HERE=$(cd "$(dirname "$0")/.." && pwd)
PGB=${PGBENCH:-/opt/homebrew/opt/postgresql@17/bin/pgbench}; PORT=${PGPORT_EXP:-55499}
mkdir -p "$HERE/results/pgbench"
for run in $(seq 1 "$RUNS"); do
  for mode in rls owner_filter rls_plus_filter; do
    if [ "$mode" = owner_filter ]; then U=wayclub_admin; else U=wayclub_app; fi
    out="$HERE/results/pgbench/${DB}_${mode}_run${run}.txt"
    $PGB -h localhost -p "$PORT" -U "$U" -n -M prepared -c 8 -j 4 -T "$SECS" -r \
      -f "$HERE/bench/txn_${mode}.sql" "$DB" > "$out" 2>&1 || echo "pgbench failed: $out"
    printf '%s %s run%s %s\n' "$DB" "$mode" "$run" "$(grep -E '^tps' "$out" | head -1)"
  done
done
