#!/bin/sh -ef

PROFILE_DIR='/etc/spt/profiles/ovz'

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

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

list_profiles()
{
	find "$PROFILE_DIR" -mindepth 1 -maxdepth 1 -type d  ! -name '.default' -printf '("%f")\n'
}
    

list_avail_packages()
{
    [ -z "$1" ] || apt-cache --no-generate search "$1"|
	cut -f1 -d' ' |
	sort
}

list_profile_packages()
{
	[ -z "$1" -o ! -f "$PROFILE_DIR/$1/ovz/packages" ] ||
		sort "$PROFILE_DIR/$1/ovz/packages"
}

alt_list()
{
	echo '('
	case "$in__objects" in
		profiles)
			list_profiles
			;;
		*/avail_packages)
			local name="${in__objects%%/avail_packages}"
			local installed="$(mktemp -t installed.XXXXXX)"

			list_profile_packages "${name##*/}" >"$installed"
			list_avail_packages "$in_pattern" |
				comm -23 - "$installed"|
				sed 's,.*,("&"),'

			rm -rf "$installed"
			;;
		*/profile_packages)
			local name="${in__objects%%/profile_packages}"
			list_profile_packages "${name##*/}"|sed 's,.*,("&"),'
			;;
	esac
	echo ')'
}

# create new profile
alt_new()
{
	case "$in__objects" in
		/)
			if [ -d "$PROFILE_DIR/$in_name" ]; then
				printf '(error "%s)"' "`_ "Same name already in use"`"
				return
			fi
			cp -a "$PROFILE_DIR/.default" "$PROFILE_DIR/$in_name"
			;;
		*)
			echo "$in_package"|tr ';' '\n' >>"$PROFILE_DIR/${in__objects##*/}/ovz/packages"
			;;
	esac
	echo '()'
}

# delete profile
alt_delete()
{
	if [ -n "$in_package" ]; then
		local in_package="$(echo "$in_package"|sed -e 's/;/\|/g')"
		sed "/^\($in_package\)\$/ d" -i "$PROFILE_DIR/${in__objects##*/}/ovz/packages"
	elif [ -n "${in__objects##*/}" -a "${in__objects##*/}" != "/" ]; then
		rm -rf "$PROFILE_DIR/${in__objects##*/}"
	fi
	echo '()'
}

on_message()
{
	case "$in_action" in
		constraints)
			echo '('
			printf ' name (label "%s" match ("^[a-z][-a-z0-9]*$" "%s"))' \
			    "`_ "Profile name"`" \
			    "`_ "should be only small latin letters and digits"`"
			printf ' description (label "%s")' \
			    "`_ "Description"`"
			printf ' package (label "%s")' \
			    "`_ "Package"`"
			printf ' pattern (label "%s")' \
			    "`_ "Package name pattern"`"
			echo ')'
			;;
		list)
			alt_list
			;;
		write)
			echo '()'
			;;
		read)
			echo '('
			printf ' pattern "%s"' "$(echo "$in_pattern"|simple_quote)"
			echo ')'
			;;
		new)
			alt_new
			;;
		delete)
			alt_delete
			;;
		*)
			echo '#f'
			;;
	esac
}

message_loop
