#!/usr/bin/env bash
# SAMD21/51 persona pack — adom-usb FIRMWARE device-test pack (API v1). Implements: manifest, personas, flash.
# REFERENCE TEMPLATE: drop your real firmware artifacts in firmware/<persona>.<ext> and wire
# the bossac call below. Ships the flash CONTRACT; manufacturers ship the binaries.
set -euo pipefail; HERE="$(cd "$(dirname "$0")" && pwd)"
cmd="${1:-}"; shift || true
case "$cmd" in
  manifest) cat "$HERE/plugin.json";;
  personas) if command -v jq >/dev/null; then jq -c '.personas' "$HERE/plugin.json"; else grep -o '"personas".*' "$HERE/plugin.json"; fi;;
  flash)
    PERSONA="" VID="" PID="" BUSID="" TARGET=""
    while [ $# -gt 0 ]; do case "$1" in --persona)PERSONA="$2";shift 2;; --vid)VID="$2";shift 2;; --pid)PID="$2";shift 2;; --busid)BUSID="$2";shift 2;; --target)TARGET="$2";shift 2;; *)shift;; esac; done
    ART="$HERE/firmware/${PERSONA}.bin"; METHOD="bossac"
    # The real flash call (chip-specific). Degrades to a dry-run when the tool/artifact is absent.
    case "$METHOD" in
      uf2-bootsel) RUN="picotool load $HERE/firmware/${PERSONA}.uf2 -f && picotool reboot";;
      dfu-util)    RUN="dfu-util -a 0 -s 0x08000000:leave -D $ART";;
      esptool)     RUN="esptool.py --chip auto write_flash 0x0 $ART";;
      nrfutil)     RUN="nrfutil device program --firmware $ART";;
      openocd)     RUN="openocd -f board/ti_sitara.cfg -c 'program $ART verify reset exit'";;
      bossac)      RUN="bossac -e -w -v -R $ART";;
      wchisp)      RUN="wchisp flash $ART";;
      *)           RUN="<flash $ART via $METHOD>";;
    esac
    if [ -f "$ART" ] || [ -f "$HERE/firmware/${PERSONA}.uf2" ]; then eval "$RUN" >/dev/null 2>&1 && STATUS="flashed" || STATUS="flash-failed"; else STATUS="dry-run (no bundled artifact — template)"; fi
    printf '{"ok":true,"persona":"%s","method":"%s","status":"%s","command":"%s","summary":"%s: device will re-enumerate as the persona USB class — refresh adom-usb"}\n' "$PERSONA" "$METHOD" "$STATUS" "$RUN" "$PERSONA";;
  *) echo "usage: adom-usb-stub-samd21 manifest | personas | flash --persona <id> --vid <hex> --pid <hex> --busid <b> --target <host>" >&2; exit 2;;
esac
