#!/bin/sh

po_domain="alterator-control"

. alterator-sh-functions

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

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

			if [ "$retcode" -eq 0 ];then
				write_nop
			else
				write_error "`_ "facility setup failed"`"
			fi
			;;
		*)
			echo '#f'
			;;
	esac
}

message_loop
