#!/bin/sh
# cd24-lowlatency-in/src/cd24-lowlatency-cancel/cd24-lowlatency-fwupgrade.sh
# 
#  Copyright: ©2012, Güralp Systems Ltd.
#  Author: Laurence Withers <lwithers@guralp.com>
#  License: GPLv3
#
#  Script to update the firmware on a CD24 that is in low latency mode (actually
#  it will also work in BRP mode, but it is intended for low latency systems).
#  The script will first stop the receiver, then send a recovery command to get
#  into GCF mode, and then call cd24fw. It will then restart the port service.
#
#  The first argument is the port name, e.g. PortA. The second argument is
#  optional and gives the firmware filename. This will be autodetected if not
#  specified.
#

FIRMWARE_PATH="/usr/share/firmware/CMG-CD24"

case "$#" in
1)
	# TODO: ls -v won't work with the current CD24 firmware file naming
	# scheme. This will need to be revisited should be have more than one
	# file in ${FIRMWARE_PATH}, which we don't as of the time of writing.
	FIRMWARE="${FIRMWARE_PATH}/`ls -1v ${FIRMWARE_PATH} | tail -n 1`"
	;;

2)
	FIRMWARE="$2"
	;;

*)
	echo "Usage: $0 <port> [<firmware.hex>]"
	exit 1
	;;
esac

PORT="$1"
CF="/etc/conf.d/serial.local/${PORT}.cf"

if [ ! -e "${CF}" ]
then
	echo "Invalid port. Valid ports are:"
	ls /etc/conf.d/serial.local/*.cf | sed -e 's|\.cf$||' -e 's|^.*/||'
	exit 1
fi

fail() {
	echo "Failed!"
	exit 1
}

echo "Stopping port service"
svc "${PORT}" stop

echo "Sending recovery command"
DEVICE="`gcs_rwvar "gcs_get_varcf" "device" "${CF}"`"
BAUD="`gcs_rwvar "gcs_get_varcf" "baud" "${CF}"`"
cat > "${DEVICE}" <<EOF


ok-1
0 fast-sps
go
EOF
sleep 10

echo "Beginning firmware upload (${FIRMWARE})"
cd24fw "${DEVICE}" "${BAUD}" "${FIRMWARE}"
EXIT_CODE="$?"

echo "Restarting port service"
svc "${PORT}" start || fail

exit "${EXIT_CODE}"
