#!/bin/sh

po_domain="alterator-mkimage"
alterator_api_version=1

. alterator-sh-functions

list_targets()
{
	make __frontend=1 help/distro 2>/dev/null \
	| while read i; do
		write_enum_item "$i" "$i"
	done
}

list_arches()
{
	if [ "`arch`" = x86_64 ]; then
		write_enum_item "64-bit" "x86_64"
	fi
	write_enum_item "32-bit" "i586"
}

xfer_args()
{
	set \
	| sed -rn 's/^in_([A-Z_0-9]+=.*)$/\1/p' \
	| sed -e "s/'#t'/1/" -e "s/'#f'//"
}

make_target()
{
	if [ "$EUID" = 0 ]; then
		alterator-mailbox-send "message \"root builds unsupported\""
		exit 0
	fi
#xfer_args >&2
# NB: distclean happens even after a failed build
	make __frontend=1 `xfer_args` "$1" distclean 2>&1 \
	| while read -r time line; do
		alterator-mailbox-send "message \"$line\""
	done
}

for dir in ~/mkimage/mkimage-profiles /usr/share/mkimage-profiles; do
	[ -d "$dir" ] && cd "$dir" && break
done || exit 1

on_message() {
  case "$in_action" in
    read) ;;
    write)
	    if [ -n "$in_target" ]; then
		    make_target "$in_target" &
	    fi
	    ;;
    list)
	    case "$in__objects" in
	    targets) list_targets;;
	    arches)  list_arches;;
	    esac
	    ;;
  esac
}

message_loop
