#!/bin/ash -efu
#
# mki-pack-results
#
# This file is part of mkimage
# Copyright (C) 2007-2009  Alexey Gladkov <gladkov.alexey@gmail.com>
#
# This file is covered by the GNU General Public License,
# which should be included with mkimage as the file COPYING.
#

. "${0%/*}"/mki-sh-functions

verbose "has started executing."

typeslist="${MKI_PACK_RESULTS:?pack rules required}"

# Format: <MKI_PACKTYPE>[:<MKI_OUTNAME>[:[!]<SUBDIR>,...]]
# Format: custom[:<MKI_OUTNAME>:<MKI_HANDLER>[:[!]<SUBDIR>,...]]
parse() {
	local OLD_IFS="$IFS"
	local IFS=:
	local mode

	mode="$1"
	shift

	set -- $1
	IFS="$OLD_IFS"

	if [ "$#" -eq 0 ]; then
		fatal "More arguments required"
	fi

	MKI_PACKMOD="$1"; shift
	MKI_OUTNAME=
	MKI_HANDLER=
	MKI_IMAGESUBDIR=
	MKI_EXCLUDE=

	[ "$#" -gt 0 ] ||
		return 0

	MKI_OUTNAME="$1"
	shift

	if [ "$mode" = 'custom' ]; then
		MKI_HANDLER="$1"
		shift
	fi

	for a; do
		[ -n "${a##[\!]*}" ] &&
			MKI_IMAGESUBDIR="$a" ||
			MKI_EXCLUDE="$MKI_EXCLUDE ${a#[\!]}"
	done

	MKI_IMAGESUBDIR="${MKI_IMAGESUBDIR# }"
	MKI_EXCLUDE="${MKI_EXCLUDE# }"
}

run_pack() {
	local MKI_PACKMOD= MKI_PACKTYPE= MKI_OUTNAME= MKI_IMAGESUBDIR= MKI_EXCLUDE=

	case "$1" in
		custom|custom:*)
			parse 'custom' "$1"
			;;
		*)
			parse 'type' "$1"
			;;
	esac

	export MKI_OUTNAME MKI_IMAGESUBDIR MKI_EXCLUDE
	mki-pack-$MKI_PACKMOD
}

set -- $typeslist

if [ "$#" -eq 1 ]; then
	run_pack "$1"
	exit
fi

unset CLEANUP_OUTDIR

for t in "${@-}"; do
	run_pack "$t"
done
