#!/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
# shellcheck source=/bin/shell-quote
. shell-quote

verbose "has started executing."

case "$PROG" in
	*-image-*)
		scriptdir="${MKI_IMAGE_SCRIPTDIR:?Script directory required}"
		dir="$subdir"
		;;
	*)
		scriptdir="${MKI_SCRIPTDIR:?Script directory required}"
		;;
esac

if [ ! -d "$scriptdir" ]; then
	verbose "$scriptdir: not found ... ignoring!"
	exit 0
fi

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

print_global_environ() {
	verbose "Translate variables from Makefile to scripts:"

	print_environ_names | sort |
	while read -r envname; do
		case "$envname" in
			GLOBAL_*|INFO_*)
				;;
			*)
				continue
				;;
		esac

		envval=
		eval "envval=\"\$$envname\""
		quote_shell_variable envval "$envval"

		verbose "export $envname=\"$envval\""
		printf 'export %s="%s"\n' "$envname" "$envval"
	done
}

make_exec "$dir/chroot/.host/start.sh" <<EOF
#!/bin/sh -efu
$(print_global_environ)
export WORKDIR=/.image
/.host/script.sh
EOF

find "$scriptdir/" -mindepth 1 -maxdepth 1 -type f -o -type l |
	sort -n |
while read -r script; do
	[ -x "$script" ] || continue

	case "$script" in
		*~|*.bak|*.rpmnew|*.rpmsave) continue ;;
		*) ;;
	esac

	cp -f -- "$script" "$dir/chroot/.host/script.sh"
	chmod 755 -- "$dir/chroot/.host/script.sh"

	verbose "Run: \`$script'"

	env WORKDIR="$dir" \
		mki-run "/.host/start.sh" ||
			fatal "$script: unable to run script."
done

cd "$dir/chroot/.host"
rm -rf -- "start.sh" "script.sh"
