#!/bin/sh

# Create GRUB boot USB device.

# Initialize some variables.
dd=`which dd`
pkglibdir=$(eval echo /usr/lib/grub/*-*)
stage1=$pkglibdir/stage1
stage2=$pkglibdir/stage2

# I like functions.

abort()
{
        /bin/echo -e "\n$@\n" >&2
                exit 1
}

checkfiles()
{
        [ -x "$dd" ] || abort "Can't find $dd, aborting"
        [ -f "$stage1" ] || abort "Can't find $stage1, aborting"
        [ -f "$stage2" ] || abort "Can't find $stage2, aborting"
}

usage()
{
        cat <<EOF
Usage: $0 [options] <block device>
Create GRUB boot USB device.

Example: $0 /dev/sdb

options:
        -h, --help      print this message and exit

EOF
        exit 1
}

checkdevice()
{
        [ -z "$1" ] && abort "checkdevice() takes block device as parameter"

        [ -b "$1" ] || abort "$1 is not a block device, aborting"
        [ -w "$1" ] || abort "$1 is not a writeable block device, aborting"
}

questiondevice()
{
        [ -z "$1" ] && abort "questiondevice() takes block device as parameter"

        echo "You are about to overwrite the boot sector of the following device: $1"
        echo "Anything on '$1' will be lost!!!"
        echo -n "Are you sure you want to take this action (y/N) "
        read answer
        case "$answer" in
                y* | Y*)
                        # let this fall through to the next function
                        ;;
                *)
                        abort "Not continuing as you wish"
                ;;
        esac
}

createusb()
{
        [ -z "$1" ] && abort "createusb() takes block device as parameter"

        /bin/echo -e "Creating grub boot USB device...\n"

        # heres where we actually create the USB device
        $dd if="$stage1" of="$1" bs="512" count="1"
        $dd if="$stage2" of="$1" bs="512" seek="1"

        /bin/echo -e "\nThat's All Folks!"
}

case "$1" in
        -h | --help)
                usage
                ;;

        *)
                if [ -z "$1" ] ; then
                        usage
                else
						checkfiles
                        checkdevice "$1"
                        questiondevice "$1"
                        createusb "$1"
                fi
                ;;
esac

exit 0
