#!/bin/sh

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

profiledir="/var/lib/install3"

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

pipedir="/var/run/alterator-pkg"
errpipe="$pipedir/stderr.fifo"

templist=

. alterator-sh-functions

### initial actions
mkdir -p "$pipedir"
[ -p "$errpipe" ] || (rm -f "$errpipe"; mkfifo -m600 "$errpipe")

export LANG=C

### main pipe actions

### pipe handlers
exit_handler()
{
	local rc=$?
	trap - EXIT
	
	rm -f "$templist"
	killall apt-get >/dev/null 2>/dev/null ||:
	exit $rc
}

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

stderr_handler()
{
	while read -r n; do
		alterator-mailbox-send "error \"$(message_quote "$n")\""
	done <"$errpipe"
}

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=
    if [ "$#" -gt 0 ]; then
	templist="$(mktemp -t pkg-size.XXXXXX)"

	cd "$listsdir"
	    cat "$@" |
		sed -r \
		    -e '/^[[:space:]]*$/ d'\
		    -e '/^[[:space:]]*#/ d' >"$templist"
	cd - >/dev/null
    fi
    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>"$errpipe" || rc=$?
	fi
	rm -f "$tmpfile"
	echo "pkg-size:finish:$rc"
}

make_pipe()
{
    make_apt|stdout_handler
}

stop_pipe()
{
    killall -9 apt-get >&2
}

start_pipe()
{
    stop_pipe
    make_pipe&
}

on_message()
{
	case "$in_action" in
		write)
			if [ -n "$in_lists" ]; then
			    start_pipe
			else
			    stop_pipe
			    alterator-mailbox-send "message \"apt-get:status:disk-size:0k\""
			fi
			write_nop
			;;
		*)
			echo '#f'
	esac
}

message_loop
