#!/bin/sh
#############################################################
# This script programs radio module using openocd
#############################################################
path="${0%/*}"
. "$path/inc/gwhw.inc"

needRoot

testcmd2 openocd

IMAGE="${1}"
shift

if [ ! -r "${IMAGE}" ]; then
	tmp="$(ls -1td "$path/bin/beatbase"*.bin 2>/dev/null | grep -- "${IMAGE}" | head -n 1)"
	[ -z "$tmp" ] || IMAGE="$tmp"
fi

if [ ! -r "${IMAGE}" ]; then
	die "Cant read binary from: '${IMAGE}'"
fi

echo "IMAGE: ${IMAGE}"

RADIO_SWCLK="${RADIO_SWCLK:-n}"
RADIO_SWDIO="${RADIO_SWDIO:-n}"
if [ 'n' = "${RADIO_SWCLK}" ] || [ 'n' = "${RADIO_SWDIO}" ]; then
	die "Programming radio module is not supported on this board"
fi
#############################################################
# FUTURE TODO: new openocd uses libgpio instead of sysfs

openocd -s /usr/share/openocd/scripts \
-c "interface sysfsgpio" -c "sysfsgpio_swd_nums ${RADIO_SWCLK} ${RADIO_SWDIO}" \
-c "transport select swd" -f target/efm32.cfg \
-c "\$_TARGETNAME configure -work-area-phys 0x20000000 -work-area-size \$_WORKAREASIZE -work-area-backup 0" \
-c "init" -c "reset halt" -c "program ${IMAGE} 0" -c "reset run" -c shutdown \
&& echo "OK" || die "Failed"
