#!/bin/bash
# usbserial-support/src/scripts/nsp-configure.sh
# 
#  Copyright: ©2012, Güralp Systems Ltd.
#  Author: Laurence Withers <lwithers@guralp.com>
#  License: GPLv3
#

if [ $# -ne 2 ]
then
	echo "Need two arguments: path to USB stick, and serial number."
	exit 1
fi

USB_STICK="$1"
SERIAL_NUMBER="$2"

if [ ! -e "${USB_STICK}" ]
then
	echo "USB stick not found!"
	exit 1
fi

declare -a PORT_SERIAL

for i in `seq 24`
do
	PORT_SERIAL[i]="-"
done

get_usb_serial_numbers() {
	for i in /dev/ttyUSB*
	do
		udevadm info -a -n "${i}" | grep 'ATTRS{serial}' | sed -e 's/^[^"]*"//' -e 's/".*$//' | head -n 1
	done
}
USB_SERIAL_NOS="`get_usb_serial_numbers | sort`"

setup_menu() {
	local result_file="$1"
	local port_args
	local result
	
	for i in `seq 24`
	do
		port_args="${port_args} ${i} ${PORT_SERIAL[i]}"
	done

	dialog --title "NSP-RMxx ${SERIAL_NUMBER}" \
		--menu \
		"Select port and enter serial number. Select Save when finished." \
		0 0 0 \
		${port_args} \
		"Save" "Save results and exit" \
		2> "${result_file}"
	result_code="$?"
	clear
	return ${result_code}
}

DIALOG_RESULT="`mktemp`"
check_cancelled() {
	if [ $1 -ne 0 ]
	then
		echo "Cancelled."
		rm -f "${DIALOG_RESULT}"
		exit 1
	fi
}

configure_port() {
	local result_file="$1"
	local port="$2"
	local port_list
	
	for i in ${USB_SERIAL_NOS}
	do
		port_list="${port_list} ${i} Select"
	done
	
	dialog --title "Port ${port}" \
		--menu \
		"Select serial number for port ${port}, or select dash '-' for no port." \
		0 0 0 \
		"-" "Clear selection" \
		${port_list} \
		2> "${result_file}"
	[ $? -eq 0 ] || return 0
	
	PORT_SERIAL[${port}]="`cat ${result_file}`"
}

save_and_exit() {
	# write actions into a script, in case of a later failure
	local action_script="`mktemp ${HOME}/nsp-configure.XXXXXX`"
	
	echo "Writing actions to script ${action_script}"
	echo " * If saving fails for any reason, the work done mapping the ports is not"
	echo "   lost! Simply run the command:"
	echo "       . ${action_script}"
	echo "   (note the leading period '.' character) to retry."
	echo ""
	
	echo "nsp-writeconfig init '${USB_STICK}' '${SERIAL_NUMBER}'" >> "${action_script}"
	for i in `seq 1 24`
	do
		[ "${PORT_SERIAL[i]}" = "-" ] && continue
		echo "nsp-writeconfig port '${USB_STICK}' '${i}' '${PORT_SERIAL[i]}'" >> "${action_script}"
	done
	
	# exit on any further failure
	set -e
	
	# save a backup in case we do something really stupid!
	local backup="`mktemp ${HOME}/nsp-configure-backup.XXXXXX`"
	echo "Saving ${USB_STICK} backup to ${backup}"
	dd if="${USB_STICK}" of="${backup}" bs=512 count=512
	
	. "${action_script}"
	echo "Complete."
	rm -f "${action_script}"
	exit 0
}

RESULT=""

while true
do
	setup_menu "${DIALOG_RESULT}"
	check_cancelled "$?"
	
	RESULT="`cat "${DIALOG_RESULT}"`"
	case "${RESULT}" in
	[1-9]|[12][0-9])
		configure_port "${DIALOG_RESULT}" "${RESULT}"
		;;
	Save)
		save_and_exit
		;;
	*)
		echo "Unknown result! Bug in script. '${RESULT}'"
		exit 1
		;;
	esac
done
