#!/usr/bin/env bash
# Build (first time) and run the PM_K-1 EDA container with the repo mounted.
#
#   ./run.sh                 # interactive shell in hardware/kicad/
#   ./run.sh kicad-cli sch erc pm_k1_core.kicad_sch
#   ./run.sh ngspice -b sim/some.cir
#
# Override the runtime with RUNTIME=docker ./run.sh ...
set -euo pipefail

IMG="pmk1-eda:9.0"
EDA_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"   # hardware/eda
REPO_DIR="$(cd "$EDA_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" "$EDA_DIR"
fi

# Mount the whole repo so KiCad/ngspice see hardware/ ; land in hardware/kicad.
flags=(--rm -v "$REPO_DIR":/work:Z -w /work/hardware/kicad)
[[ -t 0 && $# -eq 0 ]] && flags+=(-it)
exec "$RUNTIME" run "${flags[@]}" "$IMG" "${@:-bash}"
