#!/bin/ash -efu

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

verbose "has started executing."

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

pkgs='mar propagator glibc-utils'
mki-install $pkgs ||
	fatal "faild to install packages: $pkgs."

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

cat >"$chroot/tmp/packimage.sh"<<EOF
#!/bin/sh -efu

libdir="\$(getconf LIBDIR)"
kver="\$(readlink -ev /boot/vmlinuz |sed -e 's,/boot/vmlinuz-,,')"

#FIXME
mkdir -p -- /.image/syslinux/alt0
mkmar -r / -p '/.in/${mar_modules##*/}' -o /tmp/modules -k "\$kver"

printf '%s\n' "${PROPAGATOR_VERSION:-}" > /tmp/.VERSION
sed \
	-e "s,@LIBDIR@,\$libdir," \
	-e "s,@TMPDIR@,/tmp,g" \
	< '/.in/${initfs##*/}' |
	gencpio - |
	gzip -c > /.image/syslinux/alt0/full.cz

rm -rf -- /tmp/.VERSION
EOF

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