#!/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

verbose "has started executing."

handler="${MKI_HANDLER:?handler required}"

pkgs="${PACKAGES_REQUIRED_PACK_CUSTOM:-}"

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

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

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

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

[ -x "$handler" ] ||
	fatal "$handler: not executable."

message "$handler: executable file."

install -m755 -- "$handler" "$chroot/.host/script.sh"

if [ -n "${MKI_CUSTOM_PIPE-}" ]; then
	run_chrooted "$chroot" >"$outdir/$outname"
else
	run_chrooted "$chroot"
fi <<-EOF
#!/bin/sh -efu
WORKDIR=/.image
OUTNAME='/.our/$outname'
SUBDIR='$imgsubdir'
EXCLUDE='${MKI_EXCLUDE-}'
export WORKDIR OUTNAME SUBDIR EXCLUDE
/.host/script.sh
EOF

if [ -z "${MKI_CUSTOM_PIPE-}" ]; then
	mki-copy-our2out
fi
