#!/bin/ash -efu

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

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."

addenv() {
	printenv |
		sed -ne 's/^\(INFO_[^=]\+\)=/\1\t/p' |
	while read n v; do
		printf 'export %s="%s"\n' "$n" "$(quote_shell "$v")"
	done
}

cat > "$dir/chroot/tmp/start.sh" <<EOF
#!/bin/sh -efu
$(addenv)
export WORKDIR=/.image
/tmp/script.sh
EOF

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

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

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

	verbose "Run: \`$script'"

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

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