#!/bin/sh

. /usr/share/alterator/build/backend3.sh

FACILITIES_DIR=/etc/control.d/facilities
CONTROL=/usr/sbin/control

simple_quote()
{
 sed 's,\\,\\\\,g
s,",\\",g'
}

_()
{
LANG=${in_language%%;*}.utf8 gettext "alterator-control" "$1"
}

on_message()
{
	case "$in_action" in
		constraints)
			echo '('
			if [ "$in__objects" == "/" ] ; then
			    printf 'name (label "%s")' "`_ "Facility"`"
			    printf 'summary (label "%s")' "`_ "Summary"`"
			    printf 'current (label "%s")' "`_ "State"`"
			else
			    printf 'name (label "%s")' "`_ "Available modes"`"
			    printf 'help (label "%s")' "`_ "Description"`"
			fi
			echo ')'
			;;
		list)
			if [ "$in__objects" == "/" ];then
				echo '('
				ls -1 "$FACILITIES_DIR"/*|
					while read f;
					do
						name=${f##*/}
						printf '("%s" summary "%s" current "%s")' \
							"$name" \
							"$($CONTROL $name summary)" \
							"$($CONTROL $name)"
					done
				echo ')'
			else
				local facility="${in__objects%%/*}"
				echo '('
				"$CONTROL" "$facility" list|sed -r 's,([^[:space:]]+),("\1"),g'
				echo ')'
			fi
			;;
		read)
			if [ "$in__objects" = "/" ];then
				echo '()'
			elif [ -n "${in__objects##*/*}" ];then
				"$CONTROL" "$in__objects"|sed -r "s,.*,(name \"&\" current \"&\"),"
			else
				local facility=${in__objects%%/*}
				local mode=${in__objects##*/}
				local help="$("$CONTROL" "$facility" help "$mode"|simple_quote)"
				printf '(help "%s")' "${help#$mode: }"
			fi			
			;;
		write)
			retcode=0
			local mode=${in_current:-$in_name}
			if [ -n "$mode" ];then
				"$CONTROL" "$in__objects" "$mode"
				retcode=$?
			fi
			
			if [ "$retcode" -eq 0 ];then
				echo '()'
			else
				printf '(error "%s")' "`_ "facility setup failed"`"
			fi
			;;
		*)
			echo '#f'
			;;
	esac
}


message_loop

