#!/bin/bash

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
}

pkg_size_to_file()
{
	pkg_size="$(echo "$1" | sed 's/^apt-get:status:disk-size://' | sed 's/.$//')"
	unit_of_measurement="${1: -1}"

	# cast pkg_size to integer
	exponent="$(echo "$pkg_size" | cut -sd '.' -f2 | sed -z 's/\n$//' | wc -m)"
	pkg_size="${pkg_size//.}"

	# convert to bytes
	case "$unit_of_measurement" in
		"k" ) let pkg_size*=1024 ;;
		"M" ) let pkg_size*=1024*1024 ;;
		"G" ) let pkg_size*=1024*1024*1024 ;;
		"T" ) let pkg_size*=1024*1024*1024*1024 ;;
	esac

	let pkg_size/=10**exponent

	echo "$pkg_size" > /var/lib/installer-alterator-pkg/pkg-size
}

stdout_handler()
{
	while read -r n;do
		if [[ "$n" == "apt-get:status:disk-size:"* ]]; then
			pkg_size_to_file "$n"
		fi
		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"
	echo "$in_lists" > /var/lib/installer-alterator-pkg/pkg-list
	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"

	# ignore the no free space error before partitioning the disk
	local no_space_err_msg="E: You don't have enough free space in "
	if [[ ! -e /tmp/fstab && "$(tail -n 1 /tmp/install2.log)" == "$no_space_err_msg"* && "$rc" == "100" ]]; then
		rc=1
	fi
	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&
}

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

message_loop
