#!/bin/bash

# Last updated: August 8th 2005

NEWIMAGE=newimage.img
OLDIMAGE=oldimage.img  # Name of an existing dos image
SIZEMB=8

MKDOSFS=/packages/gui/dosfs/mkdosfs
((NUMSECT= (SIZEKB = SIZEMB << 10) << 1))
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) -- if starting at 0
#      of bytes 12 through 62 (inclusive) -- if starting at 1
#      dd starts counting at 1 -- Thanks to Christian Schneider
#         for pointing this bug (which should not cause any damage)

# copy uptil the 12th byte (not including the 12th byte)
dd if=$OLDIMAGE of=$NEWIMAGE bs=1 count=11 conv=notrunc 2>/dev/null

# copy from 63 (i.e. skip first 62 bytes) to 512 bytes
# hence we need to copy 512-62=450 bytes
dd if=$OLDIMAGE of=$NEWIMAGE bs=1 skip=62 seek=62 conv=notrunc count=450 2>/dev/null

# Print the details
echo "Your floppy image is in $NEWIMAGE. When using it in iso/pxelinux, dont forget to add"
echo "\"floppy c=$CYLINDERS s=$SECTORS h=$HEADS\" to the argument of memdisk"

