#!/bin/sh

TOPDIR=`pwd`

LOOP2=/tmp/bacula_rescue_loop2
rm -rf $LOOP2
mkdir -p $LOOP2

# Assume that everything to be loaded into memory with the
# RAM disk image (initrd) is is in the roottree directory. 

echo "Creating the Initial RAM disk image.... "
if test ! -b /dev/loop2; then
  mknod /dev/loop2 b 7 2
  if [ $? != 0 ] ; then
     echo "Cannot create /dev/loop2"
     exit 1
  fi
fi

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

# add 5 Meg for extra   
ISIZE=`expr $ISIZE + 5120`
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

# cleanup any prior left over stuff
umount $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 $LOOP2
# ... and delete the lost+found directory 
rm -rf $LOOP2/lost+found 

# then we copy the contents of our roottree to this filesystem
cp -dpR roottree/* $LOOP2/
cprtn=$?

# and unmount and divorce /dev/loop2
umount $LOOP2
losetup -d /dev/loop2 
rm -rf $LOOP2

# If above copy failed, bail out
if [ $cprtn != 0 ] ; then
  echo "RAM disk build failed."
  exit 1
fi

#
# This is a newer way of creating a ramfs.  Note, it
#  overwrites the previous root ramdisk that we built.
#  If you have an older kernel, you may want to comment
#  this out.
#
(cd roottree; find . | cpio --quiet -H newc -o) >root

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
F1 boot.msg
F2 options.msg
F3 general.msg
F4 kernel.msg
label linux
  kernel vmlinuz
  append ramdisk_size=$rdsize initrd=initrd.img
label memtest86
  kernel memtest
  append -
END_OF_DATA

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

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