#!/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%/*}")"

method=
compress_prog=
case "${MKI_TAR_COMPRESS:-}" in
	lzma)                method='--lzma';  compress_prog='lzma' ;;
	bzip2|bz2|tarbz2|-j) method='--bzip2'; compress_prog='bzip2' ;;
	gzip|gz|targz|-z)    method='--gzip';  compress_prog='gzip' ;;
esac

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

mki-install tar $compress_prog

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

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

args=
[ ! -d .in ]       || args="\$args --exclude .in"
[ ! -d .host ]     || args="\$args --exclude .host"
[ ! -f .fakedata ] || args="\$args --exclude .fakedata"

exec tar --numeric-owner \$args $method -cf - .
EOF

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