#!/bin/sh


PWD="`pwd`"
SOURCE_TREE="$PWD/initrd-tree"
OUTPUT_IMAGE="$PWD/initrd.gz"
KERNEL_VERSION="$(uname -r)"
PUPPYVERSION="`cat $SOURCE_TREE/PUPPYVERSION`"


# Calculate size needed for initrd:
SIZE=`du -s -k $SOURCE_TREE | tr "\t" " " | cut -f 1 -d ' '`
# Add a bit of padding:
PAD=900 #600 #600 #160 #98 THIS IS WEIRD HAD TO INCREASE THIS FROM 160 TO 600 v2.12!!!
TRIMOFF=800
if [ -f $SOURCE_TREE/pup_$PUPPYVERSION.sfs ];then #v2.16rc
 #humongous, padding needs to be adjusted...
 PAD=3100 #1800
 TRIMOFF=0
fi

SIZE=`expr $SIZE + $PAD`

TMPSIZE=`expr $SIZE \* 3`
#TMPSIZE=`expr $TMPSIZE + 500`
mkdir /tmp/tmpfs
mount tmpfs /tmp/tmpfs -t tmpfs -o size=${TMPSIZE}k
mkdir /tmp/tmpfs/mntpt

echo "Size of ext2 filesystem is ${SIZE}KB"

# Make an empty file of the proper size:
dd if=/dev/zero of=/tmp/tmpfs/initrd-tmp bs=1k count=$SIZE #2> /dev/null
sync
# Create a filesystem on it:
mke2fs -m 0 -F /tmp/tmpfs/initrd-tmp #1> /dev/null 2> /dev/null
sync
# Fix broken ext2fs defaults:
tune2fs -c 0 -i 0 -m 0 /tmp/tmpfs/initrd-tmp #1> /dev/null 2> /dev/null
sync
# Mount the initrd-to-be:
losetup /dev/loop2 /tmp/tmpfs/initrd-tmp
mount -t ext2 /dev/loop2 /tmp/tmpfs/mntpt


  # Populate the initrd image:
  ( cd $SOURCE_TREE
    cp -a * /tmp/tmpfs/mntpt
  )

  #v2.16rc...  
  rm -f /tmp/tmpfs/mntpt/init
  ln -s sbin/init /tmp/tmpfs/mntpt/linuxrc
  if [ -d /tmp/tmpfs/mntpt/dev0 ];then
   rmdir /tmp/tmpfs/mntpt/dev
   mv /tmp/tmpfs/mntpt/dev0 /tmp/tmpfs/mntpt/dev
  fi


  #mkdir /tmp/tmpfs/mntpt/.root_ro
  #mkdir /tmp/tmpfs/mntpt/.root_rw
  ## Make sure we have any block devices that might be needed:
  #SLOPPY_DEV_LIST=$(cat /proc/partitions)
  #for device in $SLOPPY_DEV_LIST ; do
  #  if [ ! -r $SOURCE_TREE/dev/$device -a -b /dev/$device ]; then
  #    cp -a /dev/$device $SOURCE_TREE/dev
  #  fi
  #done
  
  # Unmount the initrd and move it into place:
  sync
  umount /dev/loop2
  rmdir /tmp/tmpfs/mntpt
  #gzip -9 /tmp/tmpfs/initrd-tmp
  #rm -f $OUTPUT_IMAGE
  #mv /tmp/tmpfs/initrd-tmp.gz $OUTPUT_IMAGE
  sync


#attempt size reduction, that huge empty space...
rm -f initrd
rm -f initrd.gz
DOWNSIZE=`expr $SIZE \- $TRIMOFF` #800 700
sync
resize2fs -pf /tmp/tmpfs/initrd-tmp $DOWNSIZE
sync
dd if=/tmp/tmpfs/initrd-tmp of=initrd bs=1k count=$DOWNSIZE
sync
e2fsck -y -f initrd
sync
rm -f /tmp/tmpfs/initrd-tmp
gzip -9 initrd
sync

umount /tmp/tmpfs
rmdir /tmp/tmpfs

#v2.15 save the size, needed by createpuppy...
echo -n "$SIZE" > /tmp/initrdsize.txt
sync
####END####

