#!/bin/bash
#
# Make the disk.
#
# Chris Johns (chrisj at rtems dot org)
#
#

if [ $# -ne 2 ]; then
  echo "Need to supply the image name and image size in megs."
  exit 1
fi

PATH=/sbin:/usr/sbin:$PATH

DATE=`date +%Y%m%d`

MNTPOINT=mnt-image
IMAGESIZE_IN_MEGS=$2
IMAGESIZE=`expr $IMAGESIZE_IN_MEGS \* 1024`
IMAGE=$1-$DATE.img

rm -f $IMAGE
rm -f $IMAGE.gz

dd if=/dev/zero of=$IMAGE bs=1k count=$IMAGESIZE

for devnum in 0 1 2 3 4 5 6 7 8; do
    if losetup /dev/loop$devnum $IMAGE 2>/dev/null ; then break; fi
done

if [ "$devnum" = "8" ]; then
  rm -rf $MNTPOINT $IMAGE
  echo "All of your loopback devices are in use!" >&2
  exit 1
fi

LODEV=/dev/loop$devnum

# We have to "echo y |" so that it doesn't complain about $IMAGE not
# being a block device
echo y | mkdosfs $LODEV $IMAGESIZE >/dev/null 2>/dev/null

echo "Using loopback device $LODEV"

mkdir -p $MNTPOINT
mount -t vfat $LODEV $MNTPOINT || {
  echo "Can't get a loopback device"
  exit 1
}

here=$(pwd)

cd $MNTPOINT

#
# Add files for the image here.
#

cd $here
umount $MNTPOINT
losetup -d $LODEV

