#!/bin/bash

error() {
   echo $1 
   exit 1
}

if (( `id -u` != 0 )); then
   error "Sorry, must be root.  Exiting..."
fi

SYSLINUX="../linux/usr/bin/syslinux"
FILES="../linux/boot/vmlinuz ../linux/boot/memtest ../linux/boot/initrd.gz etc/syslinux.cfg etc/message.txt etc/f1.txt"
MBR="bin/mbr.bin"
MISSING="0"

echo "Checking for necessary files"

# Must check SYSLINUX seperately since we want to be sure it is executable
echo -n "$SYSLINUX ... "
if [ -x $SYSLINUX ]; then
   echo "Found"
else
   echo "Not found!"
   let $((MISSING++))
fi

# Now checking the rest
for FILE in $FILES $MBR ; do
   echo -n "$FILE ... "
   if [ -r $FILE ]; then
      echo "Found"
   else
      echo "Not found!"
      let $((MISSING++))
   fi
done

if [ "$MISSING" != "0" ]; then
   error "$MISSING file(s) missing!  Make sure you are running this from the runtutil directory!"
fi

CUR_DEV=`df . | grep "/" | cut -d " " -f 1`
CUR_BASE=`echo $CUR_DEV | sed 's/\([^0-9]\+\)[0-9]*$/\1/'`

if [ -b $CUR_DEV -a -b $CUR_BASE ]; then
   echo Current device is $CUR_DEV
   echo Base device is $CUR_BASE
   
   echo Copying files to root of pen drive...
   for FILE in $FILES; do
      echo -n "$FILE ..."
      cp -f $FILE ..
      echo "Done"
   done

   echo Making pen drive bootable...
#   export MTOOLS_SKIP_CHECK=1
   $SYSLINUX $CUR_DEV || error "syslinux $CUR_DEV failed.  mtools is required for this script to work."
   if [ "$CUR_BASE" == "$CUR_DEV" ]; then
      echo "Warning: $CUR_DEV doesn't appear to be partitioned."
      echo "Not writing the MBR Code"
      echo "This is not a supported configuration."
      echo "It is recommended that you partition your drive"
   else
      echo Writing MBR
      dd if=$MBR of=$CUR_BASE
   fi
   echo
   echo Operation complete.  Check for any error messages.
   echo
   echo Make sure that your RUNT partition is bootable by running fdisk -l $CUR_BASE
   echo and looking for a '*' in the line for $CUR_DEV under the Boot column
   echo If it isn\'t, run fdisk $CUR_BASE, and type a ENTER, enter 1 for the
   echo partition number, and type w ENTER to save your changes.
   echo
   echo Press Enter to exit.
   read
else
   error "$CUR_DEV or $CUR_BASE is not a block device!"
fi
