#!/usr/bin/env bash
# Reproduce the measurement: throwaway container, setup, test matrix, cleanup.
# Needs docker. Output goes to raw/setup.out and raw/run.out.
# stderr is merged into stdout inside the container: docker exec carries the two
# streams separately and would otherwise print errors under the wrong statement.
set -euo pipefail
cd "$(dirname "$0")"
NAME=${NAME:-supabase-storage-rls}
# Never touch an existing container: pick a free name instead.
if docker ps -a --format '{{.Names}}' | grep -qx "$NAME"; then NAME="$NAME-2"; fi
if docker ps -a --format '{{.Names}}' | grep -qx "$NAME"; then echo "container $NAME exists, aborting" >&2; exit 1; fi
mkdir -p raw
docker run -d --name "$NAME" -e POSTGRES_USER=supabase_admin -e POSTGRES_DB=postgres \
  -e POSTGRES_PASSWORD=x postgres:17 >/dev/null
trap '[ "${KEEP:-0}" = 1 ] || docker rm -f "$NAME" >/dev/null' EXIT
until docker exec "$NAME" pg_isready -U supabase_admin -d postgres -q; do sleep 1; done
sleep 2   # the entrypoint restarts the server once after init
until docker exec "$NAME" pg_isready -U supabase_admin -d postgres -q; do sleep 1; done
docker exec -i "$NAME" sh -c 'psql -X -e -U supabase_admin -d postgres 2>&1' < setup.sql > raw/setup.out
docker exec -i "$NAME" sh -c 'psql -X -e -U supabase_admin -d postgres 2>&1' < run.sql > raw/run.out
echo "done ($NAME): raw/setup.out raw/run.out"
