#!/usr/bin/env bash
# Build pm-grid for the RP2040 and produce pm-grid.uf2.
# Flash: hold BOOTSEL on the Pico, plug in USB, drag pm-grid.uf2 onto the RPI-RP2 drive.
#
#   ./build.sh
#
# Override the runtime with RUNTIME=docker ./build.sh
set -euo pipefail

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

"$RUNTIME" run --rm -v "$REPO":/work:Z -w /work/rust/pm-grid "$IMG" bash -c '
  set -e
  rustup component add llvm-tools-preview >/dev/null 2>&1 || true
  cargo build --release
  OBJCOPY="$(rustc --print sysroot)/lib/rustlib/$(rustc -vV | sed -n "s/host: //p")/bin/llvm-objcopy"
  "$OBJCOPY" -O binary target/thumbv6m-none-eabi/release/pm-grid pm-grid.bin
  cp target/thumbv6m-none-eabi/release/pm-grid pm-grid.elf   # ELF for probe-rs flash + defmt decode
'
python3 "$DIR/uf2.py" "$DIR/pm-grid.bin" "$DIR/pm-grid.uf2"
echo "→ $DIR/pm-grid.uf2  (hold BOOTSEL on the Pico, drag this onto the RPI-RP2 drive)"
