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

# shellcheck source=tools/mki-sh-functions
. "${0%/*}"/mki-sh-functions

verbose "has started executing."

pkgs="${PACKAGES_REQUIRED_PACK_CPIO:-}"

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

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

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

case "${MKI_CPIO_COMPRESS:-}" in
	xz)
		compress='xz'
		pkgs="$pkgs ${PACKAGES_REQUIRED_PACK_XZ:-}"
		;;
	gzip|gz)
		compress='gzip'
		pkgs="$pkgs ${PACKAGES_REQUIRED_PACK_GZIP:-}"
		;;
	bzip2|bz2)
		compress='bzip2'
		pkgs="$pkgs  ${PACKAGES_REQUIRED_PACK_BZIP2:-}"
		;;
	zst|zstd)
		compress='zstd'
		pkgs="$pkgs ${PACKAGES_REQUIRED_PACK_ZSTD:-}"
		;;
	lz4)
		compress='lz4'
		pkgs="$pkgs ${PACKAGES_REQUIRED_PACK_LZ4:-}"
		;;
	*)
		compress='cat'
		;;
esac

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

mki-install $pkgs ||
	fatal "failed to install packages: $pkgs."

run_chrooted "$chroot" > "$outdir/$outname" <<EOF
#!/bin/sh -efu
cd /.image/

[ -z "$imgsubdir" ] || [ ! -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"

for dir in ${MKI_EXCLUDE:-}; do
	args="\${args:+\$args -a} ! -wholename ./\${dir#/}"
done

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