#!/bin/ash -efu
#
# mki-build-propagator
#
# This file is part of mkimage
# Copyright (C) 2007-2009  Alexey Gladkov <gladkov.alexey@gmail.com>
#
# This file is covered by the GNU General Public License,
# which should be included with mkimage as the file COPYING.
#

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

verbose "has started executing."

pkgs="${PACKAGES_REQUIRED_BUILD_PROPAGATOR:-}"
mar_modules="${PROPAGATOR_MAR_MODULES:?Mar morules required}"
initfs="${PROPAGATOR_INITFS:?initfs required}"

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

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

cp -pLft "$chroot/.in/" -- "$mar_modules" "$initfs"

make_exec "$chroot/.host/packimage.sh" <<EOF
#!/bin/sh -efu${verbose:+x}

libdir="\$(getconf LIBDIR)"

if [ -L /boot/vmlinuz ]; then
	kimage="\$(readlink -ev /boot/vmlinuz)"
else
	kimage="\$(find /boot -type f -name 'vmlinuz-*' -print -quit)"
fi
kver="\${kimage#/boot/vmlinuz-}"

if type mkmodpack >/dev/null 2>&1; then
	mkmodpack -p '/.in/${mar_modules##*/}' -o /tmp/modules -k "\$kver"
else
	mkmar -r / -p '/.in/${mar_modules##*/}' -o /tmp/modules -k "\$kver"
fi

printf '%s\n' "${PROPAGATOR_VERSION:-}" > /tmp/.VERSION

rm -f /boot/full.cz

[ ! -f /tmp/modules ] ||
	cat "\$libdir/propagator/initfs" /tmp/modules > /boot/full.cz

sed \
	-e "s,@LIBDIR@,\$libdir," \
	-e "s,@TMPDIR@,/tmp,g" \
	< '/.in/${initfs##*/}' |
	gencpio - |
	gzip -c >> /boot/full.cz

rm -rf -- /tmp/.VERSION
EOF

rc=0
mki-run "/.host/packimage.sh" || rc=$?
rm -f -- "$chroot/.host/packimage.sh"
find "$chroot/.in" -mindepth 1 -maxdepth 1 -exec rm -rf -- '{}' '+'
exit $rc
