#!/usr/bin/env bash
# Build pm-daisy for the Daisy Seed (STM32H750, Cortex-M7F) and produce pm-daisy.bin + .elf.
#
#   ./build.sh                       # build for the default board revision (Seed 1.1 / WM8731)
#   ./build.sh seed                  # original Seed (AK4556)
#   ./build.sh seed_1_2              # Seed 1.2 / Seed2 DFM (PCM3060)
#
# Flash (pick one — see README.md):
#   probe-rs run --chip STM32H750VBTx pm-daisy.elf     # debug probe + defmt logs over RTT
#   dfu-util -a 0 -s 0x08000000:leave -D pm-daisy.bin -d ,0483:df11   # USB DFU (hold BOOT, tap RESET)
#
# Override the runtime with RUNTIME=docker ./build.sh
set -euo pipefail

DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"   # rust/pm-daisy
REPO="$(cd "$DIR/../.." && pwd)"                       # repo root
RUNTIME="${RUNTIME:-podman}"
IMG="pm-rust:2"
REV="${1:-seed_1_1}"   # board revision feature

"$RUNTIME" run --rm -v "$REPO":/work:Z -w /work/rust/pm-daisy "$IMG" bash -c "
  set -e
  rustup target add thumbv7em-none-eabihf >/dev/null 2>&1 || true
  rustup component add llvm-tools-preview >/dev/null 2>&1 || true
  cargo build --release --no-default-features --features '$REV'
  OBJCOPY=\"\$(rustc --print sysroot)/lib/rustlib/\$(rustc -vV | sed -n 's/host: //p')/bin/llvm-objcopy\"
  \"\$OBJCOPY\" -O binary target/thumbv7em-none-eabihf/release/pm-daisy pm-daisy.bin
  cp target/thumbv7em-none-eabihf/release/pm-daisy pm-daisy.elf
  echo '--- size ---'
  \"\$(dirname \"\$OBJCOPY\")/llvm-size\" target/thumbv7em-none-eabihf/release/pm-daisy
"
echo "→ $DIR/pm-daisy.bin + pm-daisy.elf  (revision: $REV)"
echo "  flash: see the header of this script / README.md"
