#!/bin/sh
#
# Script for making a memtest86 boot floppy using GRUB as bootloader
#

# (c) 2003 Peter Loje Hansen <pl@2m.dk>
#  - original version
# (c) 2004 Yann Dirson <dirson@debian.org>
#  - added parameters
#  - ability to work on a floppy image instead of a real floppy

# BUGS:
# - relies on identical device name between linux and grub, works for
#   fd0 at least

set -e


MEMTEST=/boot/memtest86+.bin
DEVICE=fd0
FLOPPYIMAGE=/dev/$DEVICE
FSTYPE=ext2

error()
{
    echo >&2 "$0: $*"
    exit 1
}

needsarg()
{
    [ $1 -ge 2 ] || error "syntax error"
}

[ -d /usr/lib/grub ] || error "Can't find /usr/lib/grub - did you install the grub package ?"

while [ $# -gt 0 ]
do
    case "$1" in
    --help) echo "$0 [--memtest $MEMTEST] [--floppyimage $FLOPPYIMAGE] [--fstype $FSTYPE]"; exit 0 ;;
    --memtest) needsarg $#; MEMTEST="$2"; shift ;;
    --floppyimage) needsarg $#; FLOPPYIMAGE="$2"; shift ;;
    --fstype) needsarg $#; FSTYPE="$2"; shift ;;
    *) error "syntax error" ;;
    esac
    shift
done

MOUNTPOINT=$(mktemp -d)

if [ -b "$FLOPPYIMAGE" ]
then
    ISFILE=0
else
    ISFILE=1
fi

if [ $ISFILE = 1 ]; then
    MOUNTOPTS="-o loop"
else
    MOUNTOPTS=""

    echo
    echo "Insert a writable floppy and press enter"
    read
fi

echo "* Creating $FSTYPE file system"
echo
/sbin/mkfs.$FSTYPE -q $FLOPPYIMAGE

mount -t $FSTYPE $MOUNTOPTS $FLOPPYIMAGE $MOUNTPOINT
mkdir -p $MOUNTPOINT/boot/grub

echo
echo "* Installing GRUB files"
cat > $MOUNTPOINT/boot/grub/menu.lst <<EOF
color green/black light-green/black
default 0
timeout 10
title  memtest
kernel ($DEVICE)/boot/$(basename $MEMTEST)
EOF
cp -vp /usr/lib/grub/i386-pc/stage? $MOUNTPOINT/boot/grub

echo
echo "* Installing $MEMTEST"
cp -v /boot/$(basename $MEMTEST) $MOUNTPOINT/boot
umount $MOUNTPOINT
rmdir $MOUNTPOINT

echo
echo -n "* Installing GRUB"
/sbin/grub --batch --device-map=/dev/null <<EOF
device ($DEVICE) $FLOPPYIMAGE
root ($DEVICE)
setup ($DEVICE)
quit
EOF
