#!/bin/sh
# remote-assist/src/remote-assist/remote-assist
# 
#  Copyright: ©2012, Güralp Systems Ltd.
#  Author: Laurence Withers <lwithers@guralp.com>
#  License: GPLv3
#

AUTOSTART="/etc/init.local/autostart"
WATCH_SOCKET="/var/run/remote-assist.watch"



show_some_help() {
	cat <<EOF
Run this script without arguments to enable the remote assist mode and
watch its progress. Press Ctrl-C when finished watching (it will still
be connected in the background).

Run this script with one argument to perform a specific action:
	remote-assist enable
		Enable the remote assist mode.
	remote-assist disable
		Disable the remote assist mode.
	remote-assist watch
		Watch the progress of the remote assist mode.
EOF
}



enable_remote_assist() {
	echo "Enabling remote assist mode."

	# force stop any running service
	svc remote-assist stop >/dev/null 2>&1
	rm -f "${WATCH_SOCKET}"

	# enable in autostart
	Q="`mktemp ${AUTOSTART}.XXXXXX`"
	grep -v "^remote-assist" < "${AUTOSTART}" > "${Q}"
	echo "remote-assist" >> "${Q}"
	mv "${Q}" "${AUTOSTART}"
	[ $? -eq 0 ] || return 1

	# start service
	svc remote-assist start

	# wait for watch socket
	for i in 1 2 3 4 5
	do
		[ -e "${WATCH_SOCKET}" ] && break
		sleep 1
	done

	if [ ! -e "${WATCH_SOCKET}" ]
	then
		echo "Unable to start service." >&2
		return 1
	fi

	return 0
}



disable_remote_assist() {
	echo "Disabling remote assist mode."

	# force stop any running service
	svc remote-assist stop >/dev/null 2>&1
	rm -f "${WATCH_SOCKET}"

	# disable in autostart
	Q="`mktemp ${AUTOSTART}.XXXXXX`"
	grep -v "^remote-assist" < "${AUTOSTART}" > "${Q}"
	mv "${Q}" "${AUTOSTART}"
}



watch_remote_assist() {
	echo "Watching progress. Press Ctrl-C to stop watching (remote assist"
	echo "will continue in background)."

	exec remote-assist-watcher "${WATCH_SOCKET}"
}



if [ $# -eq 0 ]
then
	show_some_help
	enable_remote_assist
	STATUS=$?
	[ "${STATUS}" -ne 0 ] && exit "${STATUS}"
	watch_remote_assist
	exit $?
fi

if [ $# -eq 1 ]
then
	case "$1" in
	enable|--enable)
		enable_remote_assist
		;;
	disable|--disable)
		disable_remote_assist
		;;
	watch|--watch)
		watch_remote_assist
		;;
	*)
		echo "Unknown command '$1'"
		show_some_help
		exit 1
	esac
	exit $?
fi

show_some_help
exit 1
