#!/bin/ash -efu

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

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

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

cat >"$chroot/.host/packimage.sh"<<EOF
#!/bin/sh -efu
imgdir=/.image
if [ -n "$imgsubdir" ]; then
	if [ ! -d "/.image/$imgsubdir" ]; then
		printf '%s: %s: Directory not found\\n' '$PROG' '/$imgsubdir' >&2
		exit 1
	fi
	imgdir="/.image/$imgsubdir"
fi
cd /.our
/.host/find -mindepth 1 -maxdepth 1 -exec rm -rf -- '{}' '+'
[ -z '$outname' ] ||
	mkdir -p -- '/.our/$outname'
/.host/find "\$imgdir/" \\
	-mindepth 1 -maxdepth 1 \\
	\\( \\
		\\! -wholename '/.image/.in'  -a \\
		\\! -wholename '/.image/.out' -a \\
		\\! -wholename '/.image/.host'   \\
	\\) \\
	-exec cp -alt '/.our/$outname' -- '{}' '+'
EOF

mki_exec_once "$chroot/.host/packimage.sh"
mki-copy-our2out
