#!/bin/sh -ef

CONFIG=/etc/sysconfig/alterator-@module@

################### shell file helpers

shell_add_or_subst()
{
	local name="$1" && shift
	local value="$1" && shift
	local file="$1" && shift

	[ -f "$file" ] || touch "$file"
	if grep -qs "^$name" "$file"; then
		/bin/sed -r -i "s,^$name.*,$name$value," -- "$file"
		return 0
	fi
	echo "$name$value" >> "$file"
}

################### debug

debug()
{
	[ -n "$DEBUG" ] && echo $* >&2
}

################### should also be a library function

start() { echo '('; }
stop() { echo ')'; }
nope() { echo '#f'; }
nop() { echo '()'; }

################### settings helpers

read_settings()
{
	start

	if [ -s "$CONFIG" ]; then
		echo 'check #t'

		( HELLO=
		  . "$CONFIG"
		  printf 'hello "%s"' "$HELLO"
		)

	fi

	stop
}

write_settings()
{
	# no more really
	if [ "$in_check" = "#f" ]; then
		rm -f "$CONFIG"
	else 
		local HELLO=
		if [ -n "$in_hello" ]; then
			# well, upcase it before storing :)
			HELLO="`echo $in_hello | tr [:lower:] [:upper:]`"
		fi
		shell_add_or_subst "HELLO=" "$HELLO" "$CONFIG"
	fi
	nop
}

constraints()
{
	# better ask inger@ or look elsewhere :)
	local required="$([ "$in_orig_action" = "new" ] && echo "#t" || echo "#f")"
	start
	printf 'hello (required #f match ("^[[:alnum:]]+$" "%s") label "%s")' \
	"`_ "weird hello :)"`" "`_ "Hello World"`"
	stop
}

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

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

on_message()
{
	case "$in_action" in
		constraints)
			constraints;;
		# cases below might want to check "$in__objects", etc
		list)
			nop;;
		read) 
			read_settings;;
		write)
			write_settings;;
		new|delete)
			nop;;
		*)
			nope;;
	esac
}

message_loop

