#! /bin/sh

set -e

die() {
	echo >&2 "$@"
	exit 1
}

usage() {
	echo >&2 "Usage:"
	echo >&2 "       $0 introspect"
	echo >&2 "       $0 status"
	echo >&2 "       $0 take-over"
	echo >&2 "       $0 give-back"
	echo >&2 "       $0 {freeze|unfreeze} [reason]"
	echo >&2 "       $0 send-msg text..."
	exit 1
}

if [ "$#" -lt 1 ]; then
	usage
fi
action="$1"
shift

call_twcs() {
	m="$1"
	shift
	gdbus call --system --dest com.xorcom.TwinstarCorosync --object-path /com/xorcom/TwinstarCorosync --method "$m" "$@"
}

clean_call_twcs() {
	result=`call_twcs "$@"`
	echo "$result" | sed -e 's/^(//' -e 's/,*)$//'
}

waitfor_no_transition() {
	max_timeout=60
	echo >&2 -n "Wait: "
	for i in `seq 1 "$max_timeout"`; do
		t=`$0 status | sed -n 's/^InTransition:[ \t]*//p'`
		if [ "$t" = 'false' ]; then
			echo >&2 "done"
			return
		fi
		echo >&2 -n "."
		sleep 1
	done
	echo >&2 "E: TIMEOUT"
}

case "$action" in
introspect)
	gdbus introspect --system --dest com.xorcom.TwinstarCorosync --object-path /com/xorcom/TwinstarCorosync 
	;;
status)
	clean_call_twcs org.freedesktop.DBus.Properties.GetAll com.xorcom.TwinstarCorosync | \
		sed \
			-e 's/^{//'	     \
			-e 's/}$//'	     \
			-e 's/, */\n/g'	     \
			| sed \
			-e "s/[ \t]\+/\t/"   \
			-e "s/^[\']//"       \
			-e "s/[\']:/:/"      \
			-e "s/\t</\t/"       \
			-e "s/>$//"          \
			| sort -d
	;;
take-over)
	ret=`clean_call_twcs com.xorcom.TwinstarCorosync.TakeOver`
	echo "$action=$ret"
	;;
give-back)
	ret=`clean_call_twcs com.xorcom.TwinstarCorosync.GiveBack`
	echo "$action=$ret"
	;;
freeze)
	if [ "$#" -gt 0 ]; then
		msg="$*"
	else
		msg=""
	fi
	ret=`clean_call_twcs com.xorcom.TwinstarCorosync.SetFreeze true "$msg"`
	echo "$action=$ret"
	;;
unfreeze)
	ret=`clean_call_twcs com.xorcom.TwinstarCorosync.SetFreeze false ""`
	echo "$action=$ret"
	;;
send-msg)
	[ "$#" -eq 1 ] || usage
	msg="$1"
	clean_call_twcs com.xorcom.TwinstarCorosync.SendMessage "$msg"
	;;
wait)
	waitfor_no_transition
	;;
monitor)
	gdbus monitor --system --dest com.xorcom.TwinstarCorosync --object-path /com/xorcom/TwinstarCorosync
	;;
esac
