#!/bin/ash -efu

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

verbose "has started executing."

outname="${MKI_OUTNAME:-outname}"
outname="${outname##*/}"

imgsubdir="${MKI_IMAGESUBDIR:-}"
imgsubdir="${imgsubdir#/}"

[ "$MKI_OUTNAME" = "${MKI_OUTNAME##*/}" ] ||
	outdir="$(readlink -ev "${MKI_OUTNAME%/*}")"

compress='cat'
case "${MKI_CPIO_COMPRESS:-}" in
	gzip|gz)
		compress='gzip'
		mki-install gzip
		;;
	bzip2|bz2)
		compress='bzip2'
		mki-install bzip2
		;;
esac

[ -d "$chroot" ] ||
	fatal "$dir: not look like a work directory of hasher."

mki-install cpio

cat >"$chroot/.host/packimage.sh"<<EOF
#!/bin/sh -efu
cd /.image/

[ -z "$imgsubdir" -o ! -d "./$imgsubdir" ] || cd "./$imgsubdir"

args=
[ ! -d .in ]       || args="\${args:+\$args -a} ! -wholename ./.in"
[ ! -d .host ]     || args="\${args:+\$args -a} ! -wholename ./.host"
[ ! -f .fakedata ] || args="\${args:+\$args -a} ! -wholename ./.fakedata"

find . -mindepth 1 \$args -print0 -o -prune |
	cpio $verbose -0 -o -c |
	$compress
EOF

mki_exec_once "$chroot/.host/packimage.sh" > "$outdir/$outname"
