#!/usr/bin/env bash
# Build (first time) and run the PM Rust container with the repo mounted.
#
#   ./run.sh                 # cargo test (runs the golden-vector conformance suite)
#   ./run.sh cargo build
#   ./run.sh bash            # interactive shell in rust/track-format/
#
# Override the runtime with RUNTIME=docker ./run.sh ...
set -euo pipefail

IMG="pm-rust:2"
RUST_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"   # rust/
REPO_DIR="$(cd "$RUST_DIR/.." && pwd)"                     # repo root
RUNTIME="${RUNTIME:-podman}"

if ! "$RUNTIME" image inspect "$IMG" >/dev/null 2>&1; then
  echo ">> building $IMG (first run, a few minutes)…" >&2
  "$RUNTIME" build -t "$IMG" "$RUST_DIR"
fi

# Mount the whole repo so the crate's tests can read tests/fixtures/ ; land in the crate dir.
flags=(--rm -v "$REPO_DIR":/work:Z -w /work/rust/track-format)
[[ -t 0 ]] && flags+=(-it)
if [[ $# -eq 0 ]]; then set -- cargo test; fi   # default command (multi-word, so set positional args)
exec "$RUNTIME" run "${flags[@]}" "$IMG" "$@"
