#!/bin/sh

TOPDIR=`pwd`

mkdir -p /mnt/loop1 /mnt/loop2

# we need to set aside a few loop devices. I chose (in reverse order of their appearance)
# -- loop1 for the boot image
# -- loop2 for the RAM disk image
# since the loop1 choice is reflected in the lilo.loopfix file, 
# you should not change that (or you need to change the file).
# I had used loop0 first, but I found that this is used by the Samba daemon.
# Also, I assume that the mount points are /mnt/loop{1,2}.
# In principle we could do with one, but it comes in handy to be able to
# leave one mounted, so I took two different ones. 

# we first assume that a proper directory tree of the later RAM disk 
# is in the initrdtree directory. Put everything in there what you think
# will be needed. We assume that this is the case.

echo "Creating the Initial RAM disk image.... "

# first find out how much space we need. 
ISIZE=`du -s -k  roottree/ | awk '{print $1}'`

# add 2 Meg for extra   
ISIZE=`expr $ISIZE + 2048`
echo "Initial RAM disk contents will be $ISIZE KB"

# delete the existing RAM disk image, if there is one
rm -f root

dd if=/dev/zero of=$TOPDIR/root bs=1k count=$ISIZE

umount /mnt/loop2  2>/dev/null >/dev/null
losetup -d /dev/loop2 2>/dev/null >/dev/null

# associate it with /dev/loop2
losetup /dev/loop2 $TOPDIR/root

# make an ext2 filesystem on it. Set reserve to 0
mke2fs -q -m 0 /dev/loop2 $ISIZE
if [ $? != 0 ] ; then
  echo "Build failed."
  exit 1
fi

# we mount it...
mount /dev/loop2 /mnt/loop2 

# ... and delete the lost+found directory 
rm -rf /mnt/loop2/lost+found 

# then we copy the contents of our roottree to this filesystem
cp -dpR roottree/* /mnt/loop2/
if [ $? != 0 ] ; then
  echo "RAM disk build failed."
  exit 1
fi

# and unmount and divorce /dev/loop2
umount /mnt/loop2
losetup -d /dev/loop2 

echo "Building initial RAM disk done"

# Now we have the image of the RAM disk in $TOPDIR/loopfiles/root. We
# compress this one and write the compressed image to the boot tree:

echo "Compressing the RAM disk image.... "

# delete any existing one
rm -f cdtree/boot/isolinux/initrd.img

# and gzip our RAM disk image and put it in the right place.
gzip -9 -c root >cdtree/boot/isolinux/initrd.img
if [ $? != 0 ] ; then
  echo "Build failed"
  exit 1
fi

rdsize=`expr $ISIZE \* 1024`
echo "Ramdisk size is $rdsize"

echo "Making isolinux.cfg"
cat >cdtree/boot/isolinux/isolinux.cfg <<END_OF_DATA
default linux
prompt 1
display boot.msg
timeout 300
label linux
  kernel vmlinuz
  append ramdisk_size=$rdsize initrd=initrd.img
END_OF_DATA

# we are done with the RAM disk image, delete it
rm -f root

echo "Initial RAM disk initrd.img is built."
