#!/bin/sh
set -e

IMAGES=/boot/images

if [ -e "/etc/default/grub-imageboot" ]
then
	. /etc/default/grub-imageboot
fi

. /usr/lib/grub/grub-mkconfig_lib
if test -e /boot/memdisk ; then
	MEMDISKPATH=$( make_system_path_relative_to_its_root "/boot/memdisk" )
	echo "Found memdisk: $MEMDISKPATH" >&2
	if [ ! -d "$IMAGES" ]; then
		echo "Imagepath $IMAGES not found" >&2
		exit
	fi
	find $IMAGES -name "*.iso" -o -name '*.img' | sort | 
	while read image ; do
		IMAGEPATH=$( make_system_path_relative_to_its_root "$image" )
		case "$image" in
			*.iso)
				echo "Found iso image: $image" >&2
				test -z "$ISOOPTS" && ISOOPTS="iso"
				cat << EOF
menuentry "Bootable ISO Image: $(basename $IMAGEPATH | sed s/.iso//)" {
EOF
				prepare_grub_to_access_device ${GRUB_DEVICE_BOOT} | sed -e "s/^/\t/"
				cat << EOF
	linux16 $MEMDISKPATH $ISOOPTS
	initrd16 $IMAGEPATH
}
EOF
				;;
			*.img)
				echo "Found floppy image: $image" >&2
				test -z "$IMAGEOPTS" && IMAGEOPTS="rawimg"
				cat << EOF
menuentry "Bootable Floppy Image: $(basename $IMAGEPATH | sed s/.img//)" {
EOF
				prepare_grub_to_access_device ${GRUB_DEVICE_BOOT} | sed -e "s/^/\t/"
				cat << EOF
	linux16 $MEMDISKPATH $IMAGEOPTS
	initrd16 $IMAGEPATH
}
EOF
				;;
		esac
	done
else 
	echo "memdisk not found" >&2
	echo "Please copy /usr/lib/syslinux/memdisk to /boot/memdisk" >&2 
fi
