#!/bin/sh -efu
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright (C) 2007-2023  Alexey Gladkov <gladkov.alexey@gmail.com>

# shellcheck source=tools/mki-sh-functions
. "${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."

args=
for d in ${MKI_EXCLUDE:-}; do
	args="$args -a \\! -wholename '$d'"
done

run_chrooted "$chroot" <<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'   \\
		$args \\
	\\) \\
	-exec cp -alt '/.our/$outname' -- '{}' '+'
EOF

mki-copy-our2out
