#!/bin/bash

error() {
   echo $1
   rmdir $MOUNTPOINT
   rm $TMPFILE
   exit 1
}

TMPFILE=`mktemp` || error "Cannot create temporary file"
MOUNTPOINT=`mktemp -d` || error "Cannot create temporary directory"

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

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

echo "Checking for necessary files"

#Need to test Syslinux separately because it needs to be executable
echo -n "$SYSLINUX ... "
if [ -x $SYSLINUX ]; then
   echo "Found"
else
   echo "Not found!"
   let $((MISSING++))
fi 

#Now check the rest
for FILE in $FILES ; 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

if [ "$#" -ge "1" ]; then
   DEVICE=$1
else
   echo -n "Type your floppy device: "
   read DEVICE
fi

if [ ! -b $DEVICE ]; then
   error "$DEVICE is not a valid block device.  Exiting..."
fi 

SIZE=`blockdev --getsize $DEVICE`
if [ ! "$SIZE" == "2880" ]; then
   error "$DEVICE does not appear to be a floppy disk.  Exiting..."
fi

umount $DEVICE

if `grep $DEVICE /etc/mtab`; then
   error "$DEVICE cannot be unmounted.  Exiting..."
fi


echo "Creating FAT filesystem in $TMPFILE"
mkdosfs -C -n RUNT $TMPFILE 1440 || error "$DEVICE failed to format.  Exiting..."

echo "Installing syslinux on $DEVICE"
#export MTOOLS_SKIP_CHECK=1
$SYSLINUX $TMPFILE || error "syslinux $TMPFILE failed.  mtools is required for this script to work."


if mount -o loop -t msdos $TMPFILE $MOUNTPOINT; then
   echo "Copying files to $MOUNTPOINT"
   for FILE in $FILES; do
      echo -n "$FILE ..."
      cp $FILE $MOUNTPOINT
      echo "Done"
   done
   echo "Unmounting drive"
   umount $TMPFILE
else
   rm $TMPFILE
   rmdir $MOUNTPOINT
   error "Unable to mount $DEVICE.  Exiting..."
fi

echo "Copying $TMPFILE to $DEVICE"
dd if=$TMPFILE of=$DEVICE bs=1440k count=1

rmdir $MOUNTPOINT
rm $TMPFILE
echo
echo "Operation Complete.  Check for any error messages."
echo
echo "Press Enter to exit."
read
