#!/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_api_version=1

. 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 -9 apt-get >/dev/null 2>/dev/null ||:
	exit $rc
}

message_quote()
{
    echo "$1"|string_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="$(mktemp -t pkg-size.XXXXXX)"

	cd "$listsdir"
	    cat "$@" ".base" |
		sed -r \
		    -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>"$errpipe" || 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
