#!/bin/sh

#### functions #####
function usage()
{
	        cat <<EOF
usage : rebuild_initrd 
EOF
        exit $1
}

if [ $# -gt 0 ]
then
	usage 1
fi

if [ -f /etc/iboot.conf ]
then
. /etc/iboot.conf
else
	KVER=`uname -r`
fi

dt=`date +%m%d%Y-%H:%M:%S`
cur=`pwd`

drivers="bnx2"

mkdir -p /tmp/ramdisk$dt
cd /tmp/ramdisk$dt
if [ $? -ne 0 ]
then
	echo "ERROR: Failed to change directory to /tmp/ramdisk$dt"
	exit 1;
fi
echo "Rebuilding /boot/initrd-$KVER..."
zcat /boot/initrd-$KVER | cpio -idv &> /dev/null
if [ $? -ne 0 ]
then
	echo "ERROR: Failed to extract the initrd image"
	exit 1
fi

echo "Copying following driver(s) to /boot/initrd-$KVER"
dpath=
for driver in $drivers
do
	dpath=`find /lib/modules/$KVER/ -name $driver.ko`
	if [ -z $dpath ]
	then
		echo "ERROR: Failed to get info on driver $driver"
		exit 1
	fi
	driverinfo=`modinfo $driver -d`" ("`modinfo $driver -F version`")"
	echo "	$driverinfo"
	cp -f $dpath .$dpath
done

mv /boot/initrd-$KVER /boot/initrd-$KVER.$dt.orig
find . ! -name "*~" | cpio -H newc --create --quiet | gzip -9 > /boot/initrd-$KVER 
if [ $? -ne 0 ]
then
	mv /boot/initrd-$KVER.$dt.orig /boot/initrd-$KVER
	echo "ERROR: Failed to rebuild /boot/initrd-$KVER."
	exit 1
fi

echo
echo "Successfully rebuilt /boot/initrd-$KVER"
echo "Reboot the system for new driver(s) to take effect."
cd $cur
exit 0
