#!/bin/sh
# force-digitiser-timing
# 
#  Copyright: ©2012–2014, Güralp Systems Ltd.
#  Author: Laurence Withers <lwithers@guralp.com>
#  License: GPLv3
#
# Set system clock. Set connected legacy digitiser clocks.
#



#
# Utility functions
#
usage() {
	cat <<EOF

Program usage:		force-digitiser-timing <isodate>

Only works when in manual timing mode. You can set the timing mode
with the command:

    timing-setup

(which is also available through the top-level "config" command).
<isodate> is an ISO8601 date/time and may include timezone
(see http://en.wikipedia.org/wiki/ISO_8601 ).
EOF
}

log() {
	logger -t "force-digitiser-timing" -- $*
}



#
# Make sure the system is in manual timing mode.
#
TIMING_SOURCE="`cfget mode "/etc/conf.d/timing.local"`"
if [ "${TIMING_SOURCE}" != "manual" ]
then
	echo "Timing mode is not manual." >&2
	usage
	exit 1
fi



#
# Retrieve commandline argument. Set date.
#
if [ $# -ne 1 ]
then
	echo "Missing date/time." >&2
	usage
	exit 1
fi

log "Manually setting date/time to $1"
setisodate "$1"
if [ $? -ne 0 ]
then
	log "Manual set failed."
	exit 1
fi
log "Manual set succeeded."



#
# Write to the Linux system RTC. Not fatal if it fails.
#
echo "Setting battery-backed RTC"
hwclock -w -u
if [ $? -ne 0 ]
then
	echo "Battery-backed RTC could not be set."
	log "Battery-backed RTC could not be set."
else
	log "Battery-backed RTC set."
fi



#
# Connect to each digitiser in turn and set date/time.
#
for TERM in `dm24-terminal -l`
do
	echo -n "Setting time on ${TERM}... "
	expect -f /usr/share/force-digitiser-timing/force-digitiser-timing.exp "${TERM}" >&/dev/null
	if [ $? -eq 0 ]
	then
		log "Successfully set time on digitiser ${TERM}."
		echo "OK."
	else
		echo "Failed. This is expected if in serial2 mode."
		log "Failed to set time on digitiser ${TERM}."
	fi
done

log "Process completed."
exit 0
