#!/bin/bash

set -euo pipefail

VERSION="1.0"
JLINK_INSTALL_PATH="/opt/SEGGER/JLink"
GDB_CMDS="target remote localhost:2331
monitor reset
monitor halt
load
compare-sections
q
"
jlinkPID=""
TMP=""

function finish {
  if [ "$jlinkPID" != "" ]; then
          echo "Stopping Jlink"
          kill $jlinkPID
  fi
  if [ "$TMP" != "" ]; then
          echo "Cleaning tmp files"
          rm $TMP
  fi
}
trap finish EXIT

echo "Version: $VERSION"

if [ ! -e "$1" ];then
        >&2 echo "Cannot access $1, exiting"
        exit 1
fi

"$JLINK_INSTALL_PATH"/JLinkGDBServer -select USB -device MKL02Z32xxx4 -endian little -if SWD -speed 1000  > /dev/null &
jlinkPID=$!

TMP=$(mktemp /tmp/XXXXX-gdbcmd)
echo "${GDB_CMDS}" > "$TMP"

gdb-multiarch -x "$TMP" "$1"
