#!/bin/sh

apt_install="/usr/bin/apt-get --simple-output install"

profiledir="/var/lib/install3"

groupsdir="$profiledir/groups"
listsdir="$profiledir/lists"
testsdir="$profiledir/tests"


templist=

alterator_api_version=1

. alterator-sh-functions


export LANG=C


message_quote()
{
    echo "$1"|string_quote
}


stdout_handler()
{
	while read -r n;do
		alterator-mailbox-send "message \"$(message_quote "$n")\""
	done
}

trap exit_handler EXIT HUP INT QUIT TERM

make_manifest()
{
    rm -f "$templist"
    templist="$(mktemp -t pkg-size.XXXXXX)"

	cd "$listsdir"
	    paste -d\\n "$@" ".base" |
		sed -r \
		    -e '/^[[:space:]]*$/ d'\
		    -e '/-[[:space:]]*$/ d'\
		    -e '/^[[:space:]]*#/ d' >"$templist"
	cd - >/dev/null

    echo "$templist"
}

make_apt()
{
	local rc=0

	echo "pkg-size:start"
	local tmpfile="$(make_manifest $in_lists)"
	if [ -s "$tmpfile" ]; then
	    stderr_handler &
	    echo "n"|apt-get --simple-output install --manifest "$tmpfile" 2>> /tmp/install2.log || rc=$?
	else
	    echo "apt-get:status:disk-size:0k"
	fi
	rm -f "$tmpfile"
	echo "pkg-size:finish:$rc"
}

make_pipe()
{
    make_apt|stdout_handler
}

stop_pipe()
{
    killall -9 apt-get >/dev/null 2>/dev/null ||:
}

start_pipe()
{
    stop_pipe
    make_pipe&
}

# initial actions
apt-get update >&2

on_message()
{
	case "$in_action" in
		write)
			start_pipe
			;;
	esac
}

message_loop
