#!/bin/bash
set -e

INTERFACE="swd0"
HEX_FILE=""

usage() {
  echo "Usage: $0 -f <hex_file> [-i swd0|swd1]"
  exit 1
}

while getopts "f:i:h" opt; do
  case "$opt" in
    f) HEX_FILE="$OPTARG" ;;
    i)
      if [[ "$OPTARG" == "swd0" || "$OPTARG" == "swd1" ]]; then
        INTERFACE="$OPTARG"
      else
        usage
      fi
      ;;
    h) usage ;;
    *) usage ;;
  esac
done

[[ -n "$HEX_FILE" ]] || usage
[[ -f "$HEX_FILE" ]] || { echo "HEX file not found: $HEX_FILE"; exit 1; }

sudo openocd \
  -f ./raspberrypi-${INTERFACE}.cfg \
  -c "init" \
  -c "reset init" \
  -c "flash banks" \
  -c "flash write_image $HEX_FILE" \
  -c "verify_image $HEX_FILE" \
  -c "reset run" \
  -c "shutdown"

sudo openocd \
  -f ./raspberrypi-${INTERFACE}.cfg \
  -c "init" \
  -c "nrf54l.dap apreg 2 0x000 0x1" \
  -c "sleep 100" \
  -c "nrf54l.dap apreg 2 0x000 0x0" \
  -c "shutdown"

sudo openocd \
  -f ./raspberrypi-${INTERFACE}.cfg \
  -c "init" \
  -c "nrf54l.dap apreg 2 0x000 0x4" \
  -c "sleep 100" \
  -c "nrf54l.dap apreg 2 0x000 0x0" \
  -c "shutdown"

echo "Flashing complete."