#!/bin/sh

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

template_dir="/var/www/html/fbi/aptgroups"
apt_profile="/etc/alterator/apt.d/install3"

UPGRADE_PROGRESS="/var/cache/alterator/aptgroups.progress"

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

#######################################################################
# Html helpers

template() {
	local tmpl="$template_dir/$1"
	shift
	[ -s "$tmpl" ] || return 0
	sed -n -e "1,/@$1@/{ s/@$1@//; p }" "$tmpl"
	eval "$*"
	sed -n -e "/@$1@/,\${ s/@$1@//; p }" "$tmpl"
}

html_quote() {
    sed -r \
	-e 's,&,\&amp;,g' \
	-e 's,",\&quot;,g' \
	-e 's,>,\&gt;,g;' \
	-e 's,<,\&lt;,g;' $*
}

html_tag() {
	sed "1 s,.*,<$1>&,
	     $ s,.*,&</${1%% *}>,"
}

#######################################################################
error() {
	printf '(error "%s")' "$*"
}

getprofile() {
	sed -e 's/[()]//g' -e '/^[[:space:]]*$/d' -- "$apt_profile"
}

workdir=
exit_handler() {
	local rc=$?
	trap - EXIT
	[ ! -d "$workdir" ] || rm -rf -- "$workdir"
	exit $rc
}

### List
uilist() {
	local c=
	! rpmquery -- "$1" >/dev/null 2>&1 || c=' checked="yes"'

	{
	    printf '<input type="checkbox" name="%s" %s/>' "$i" "$c"	| html_tag "td"
	    printf '%s\n' "$3" | html_quote				| html_tag "td"
	}								| html_tag "tr"
}

listgroups() {
	local line i=0
	getprofile |
	while read line; do
		eval "$1" $line
		i=$(($i + 1))
	done
}

trap exit_handler HUP INT QUIT TERM EXIT
workdir="$(mktemp -dt "${0##*/}.XXXXXXXXX")"
cd "$workdir"

on_message()
{
	case "$in_action" in
		template)
			echo '('
			printf ' template "form"'

			if [ "$in__objects" = "upgrade-status" ];then # Simple mode
				if grep -qs '^110$' "$UPGRADE_PROGRESS";then
					echo ' url-redirect "/aptgroups"' # apt is done ...
				elif grep -qs '^-10$' "$UPGRADE_PROGRESS";then
					echo ' url-redirect "/aptgroups/upgrade-error"' # apt is done ...
				else
					echo ' url "aptgroups-status.html"' # in progress ...
				fi
			elif [ "$in__objects" = "upgrade-status2" ];then # AJAX mode
				echo ' url "aptgroups-status2.html"'
			elif [ "$in__objects" = "upgrade-error" ];then
				echo ' url "aptgroups-error.html"'
				echo ' redirect "/aptgroups"'
			else
				template "aptgroups.list.html" listgroups uilist > tempfile
				printf ' url "%s"' "$workdir/tempfile"

				[ -n "$in_upgrade" ] &&
				if [ "$in_js" = "yes" ]; then
 					echo ' redirect "/aptgroups/upgrade-status2"'
				else
					echo ' redirect "/aptgroups/upgrade-status"'
				fi
			fi
			echo ')'
			;;
		info)
			echo '('
			printf ' title "%s"' "`_ "APT groups"`"
			printf ' group "%s"' "`_ "APT groups"`"
			printf ' description "%s\n%s"' "`_ "APT groups setup"`"
			echo ')'
			;;
		*)
			echo '#f'
			;;
	esac
}

message_loop
