#!/bin/sh

### global variables

profiledir="/var/lib/install3"

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

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

pipe_pid=
templist=

. alterator-sh-functions

### pipe handlers

exit_handler()
{
    local rc=$?
    trap - EXIT
	
    rm -f "$templist"
    stop_pipe
    exit $rc
}

stdin_handler()
{
    while :; do
        [  -e "$inpipe" ] || break
    	    while read n; do
	        if [ "$n" = "q" ]; then
	    	    rm -f "$inpipe"
		    break 2
		fi
		echo "$n"
	    done < "$inpipe"
    done
}

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
    write_pipe "q"
}


### main pipe operations

make_manifest()
{
    rm -f "$templist"
    templist=
    if [ "$#" -gt 0 ];then
	templist="$(mktemp -t pkg-install.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-install:start"
	local tmpfile="$(make_manifest $in_lists)"
	if [ -s "$tmpfile" ] ;then
	    stderr_handler &
	    apt-get --simple-output install --manifest "$tmpfile"  2>"$errpipe" || rc=$?
	fi
	rm -f "$tmpfile"
	echo "pkg-install:finish:$rc"
}

make_pipe()
{
    mkdir -p "$pipedir"
    [ -p "$errpipe" ] || (rm -rf "$errpipe"; mkfifo -m600 "$errpipe")
    [ -p "$inpipe" ] || (rm -rf "$inpipe"; mkfifo -m600 "$inpipe")

    stdin_handler|make_apt|stdout_handler
}

write_pipe()
{
    if [ -n "$pipe_pid" ] && kill -0 "$pipe_pid" ;then
	[ ! -p "$inpipe" ] || echo "$in_message" >"$inpipe"
    fi
}

stop_pipe()
{
    write_pipe "q"
    killall -9 apt-get >&2
    rm -f "$errpipe" "$inpipe"
}

start_pipe()
{
    stop_pipe
    make_pipe&
    pipe_pid=$!
}

### initial actions

export LANG=C
trap exit_handler EXIT HUP INT QUIT TERM

on_message()
{
	case "$in_action" in
		write)
			case "$in__objects" in
			    /)
				if [ -n "$in_lists" ]; then
				    start_pipe
				else
				    alterator-mailbox-send "message \"pkg-install:start\""
				    alterator-mailbox-send "message \"pkg-install:finish:0\""
				fi
				;;
			    notify)
				write_pipe "$in_message"
				;;
			esac
			write_nop
			;;
		*)
			echo '#f'
	esac
}

message_loop
