#!/bin/sh -efu
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright (C) 2021  Gleb Fotengauer-Malinovskiy <glebfm@altlinux.org>

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

verbose "has started executing."

patchesdir="${MKI_IMAGE_PATCHDIR:?Patches directory required}"

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

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

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

mki-install patch ||
	fatal "failed to install patch package."

make_exec "$chroot/.host/start.sh" <<EOF
#!/bin/sh -efu

imgdir=/.image
[ -z '$imgsubdir' ] || [ ! -d '/.image/$imgsubdir' ] ||
        imgdir='/.image/$imgsubdir'
cd "\$imgdir"

patch -p1 --merge 2>/dev/null
EOF

find "$patchesdir/" -mindepth 1 -maxdepth 1 \( -type f -o -type l \) -a -name '*.patch' |
	sort -n |
while read -r patch; do
	verbose "Applying: \`$patch'"

	mki-run "/.host/start.sh" < "$patch" ||
			fatal "$patch: unable to apply patch."
done

cd "$chroot/.host"
rm -f -- "start.sh"
