#!/bin/bash
SOURCE=ramdisk
OLD=tmp
NEW=new
NEWRAMDISK=new_ramdisk
RESULT=/tftpboot/ramdisk.self

if [ -z "$1" ] ; then 
  echo 'usage: self.sh ramdisk_filename'
  exit 1
fi

if [ ! -e "$1" ] ; then
  echo "file $1 does not exist."
  exit 1
fi

SELFIMAGE=$1


mkdir -p $OLD
mkdir -p $NEW
    
dd if=$SELFIMAGE bs=64 skip=1 of=$SOURCE.gz
gunzip -v $SOURCE.gz

mount -o loop $SOURCE $OLD

dd if=/dev/zero of=$NEWRAMDISK bs=1024k count=8
/sbin/mke2fs -F -m0 $NEWRAMDISK
/sbin/tune2fs  -c 0 $NEWRAMDISK


mount -o loop $NEWRAMDISK $NEW
cd $OLD
find . -depth -print | cpio -VBpdum ../$NEW
cd ..
umount $OLD
    
umount $NEW
gzip -9 $NEWRAMDISK
/opt/eldk/usr/bin/mkimage -T ramdisk -C gzip -n "DexGate SELF image" -d $NEWRAMDISK.gz $RESULT

rm -rf $NEWRAMDISK.gz
rm -rf $SOURCE.gz
rm -rf $SOURCE
rmdir $NEW
rmdir $OLD
