#!/bin/sh

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

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

on_message()
{
	case "$in_action" in
		constraints)
			echo '('
			printf 'name (label "%s")' "$(_ "Alternative")"
			printf 'current (label "%s")' "$(_ "Candidate")"
			printf 'manual (exclude (#f current) default #f label "%s")' "$(_ "Manual setup")"
			echo ')'
			;;
		list)
			if [ "$in__objects" == "/" ];then
				echo '('
				alternatives-list | sed -ne 's,^\(.*\) points to.*,("\1"),p' | sort
				echo ')'
			elif [ "${in__objects##*/}" = "candidates" ]; then
				local alternative="/${in__objects%%/candidates*}"
				echo '('
				grep -h "^$alternative[[:space:]]" "$auto_dir"/* |
				    sed 's,[[:space:]]\+,\t,g' |
				    cut -f2| sed 's,.*,("&"),'
				echo ')'
			else
				echo '()'
			fi
			;;
		read)
			if [ "$in__objects" == "/" ];then
				echo '()'
			else
				local alternative="/$in__objects"
				local manual="#f"
				if grep -qs "^$alternative[[:space:]].*manual$" "$manual_file"; then
				    manual="#t"
				fi
				local current=$(alternatives-list "$alternative" | sed -ne 's,^.* points to \(.*\)$,\1,p') #'
				
				echo '('
				printf 'manual %s\n' "$manual"
				printf 'current "%s"\n' "$current"
				echo ')'
			fi
			;;
		write)
			local alternative="/$in__objects"
			[ -n "$in_manual" ] &&
			if [ "$in_manual" = "#t" ]; then
				(alternatives-manual "$alternative" "$in_current" && alternatives-update) &>/dev/null
			else
				(alternatives-auto "$alternative" && alternatives-update) &>/dev/null
			fi
			echo "()"
			;;
		*)
			echo '#f'
	esac
}

message_loop
