#!/bin/bash
#
# Author: Murali krishnan GANAPATHY and Carsten Grohmann
#
# Licence: GPL
#
# original version downloaded from
#     http://people.cs.uchicago.edu/~gmurali/gui/files/mkfloppyimg.sh
#
# this version: downloaded from:
#     http://www.carstengrohmann.de/
#
# $Id: mkfloppyimg.sh,v 1.1 2004/09/30 18:47:48 carsten Exp $
#
# History:
#  - original wrote by Murali krishnan GANAPATHY (date and version unknown)
#  - 20040930 Carsten Grohmann
#     - add switch to use a floppy size of 2880 kB
#     - add usage


#set -x

# path to mkdosfs
MKDOSFS=$(which mkdosfs 2> /dev/null)

# ---- NO changes below this line required ----

# check syntax
case "$1" in
  -h|--help|-?|/?)
    echo "mkfloppyimg.sh"
    echo "Usage: mkfloppyimg.sh -2880|Size OldImage NewImage "
    echo "Extend the size of a floppy image formated with FAT "
    echo " -2880    - set the size of the new image to 2880 kB"
    echo " Size     - size of the new image in MB"
    echo " OldImage - filename of an existing bootable floppy image"
    echo " NewImage - filename of the new image"
    exit
    ;;
esac

# calculate the size
if [ "$1" -eq "-2880" ]; then
  SIZEKB=2880
else
  ((SIZEKB= ($1 << 10)))
fi
((NUMSECT= SIZEKB << 1))

# check files
if [ -e $2 ]; then
  OLDIMAGE=$2
else
  echo "ERROR: Image $2 does not exist. Please select an existing floppy"
  echo "       image and try again."
  exit 1
fi

if [ "$3" ]; then
  NEWIMAGE=$3
else
  echo "ERROR: Destination image not set. Please set this option and"
  echo "       try again."
  exit 2
fi

# check mkdosfs
if [ -z "$MKDOSFS" ]; then
  echo "ERROR: mkdosfs \"${MKDOSFS}\" not found."
  exit 3
fi
if [ ! -x "$MKDOSFS" ]; then
  echo "ERROR: mkdosfs \"${MKDOSFS}\" not executable."
  exit 4
fi

MNTNEW=`mktemp -d /tmp/new.XXXXXX` # Create a mountpoint
MNTOLD=`mktemp -d /tmp/old.XXXXXX` # Create a mountpoint

# Create the filesystem
OUTLINE=`$MKDOSFS -I -v -C $NEWIMAGE $SIZEKB | grep heads`
HEADS=`echo $OUTLINE | cut -f3 -d' '`
SECTORS=`echo $OUTLINE | cut -f6 -d' '`
((CYLINDERS= NUMSECT / HEADS / SECTORS ))
# Copy contents from old image to new image
mount -o loop $NEWIMAGE $MNTNEW
mount -o loop $OLDIMAGE $MNTOLD
cp -r $MNTOLD/* $MNTNEW
umount $MNTNEW
umount $MNTOLD
rmdir $MNTNEW
rmdir $MNTOLD
# Create the boot sector of the new image
# copy the first 512 bytes from the OLD image except the bytes 11 through 61 (inclusive)
dd if=$OLDIMAGE of=$NEWIMAGE bs=1 count=10 conv=notrunc 2>/dev/null
dd if=$OLDIMAGE of=$NEWIMAGE bs=1 skip=61 seek=61 conv=notrunc count=451 2>/dev/null
# Print the details
echo "Your floppy image is in $NEWIMAGE."
if [ $SIZEKB -ne 2880 ]; then
  echo "When using it in iso/pxelinux, dont forget to add"
  echo "\"floppy c=$CYLINDERS s=$SECTORS h=$HEADS\" to the argument of memdisk."
fi
