#!/bin/sh

SCRIPTNAME=`basename $0`
SCRIPTDIR=`echo $0 | sed s/$SCRIPTNAME// | sed s/postinstall//`

echo "Determining possible kernel versions..."
KERNEL=`ls -1 /mnt/sysimage/lib/modules/        | grep -v kabi | grep -v ELsmp | grep -v hugemem`

if [ `ls -1 /mnt/sysimage/boot/vmlinuz* | grep -c smp` -eq 1 ] ; then
    KERNELSMP=`ls -1 /mnt/sysimage/lib/modules/     | grep -v kabi | grep    ELsmp | grep -v hugemem`
fi

if [ `ls -1 /mnt/sysimage/boot/vmlinuz* | grep -c hugemem` -eq 1 ] ; then
    KERNELHUGEMEM=`ls -1 /mnt/sysimage/lib/modules/ | grep -v kabi | grep -v ELsmp | grep    hugemem`
fi

if [ "$KERNEL" == "" ] ; then
    echo "*** Error: There are no kernel modules! ***"
    exit 1
else
    echo "The defalut kernel is $KERNEL"
fi

if [ "$KERNELSMP" != "" ] ; then
    echo "The SMP kernel is $KERNELSMP"
fi

if [ "$KERNELHUGEMEM" != "" ] ; then
    echo "The hugemem kernel is $KERNELHUGEMEM"
fi

echo "Copying utilities to /sbin"
echo " - mkinitrd"
cp -f $SCRIPTDIR/postinstall/sbin/mkinitrd /mnt/sysimage/sbin/
chmod 744 /mnt/sysimage/sbin/mkinitrd

echo "Copying utilities to /bin"
echo " - iscsi_boot_util"
cp -f /sbin/iscsi_boot_util /mnt/sysimage/bin/iscsi_boot_util
chmod 766 /mnt/sysimage/bin/iscsi_boot_util

echo "Copying configuration files to /etc"
echo " - ethsettings"
cp /etc/ethsettings         /mnt/sysimage/etc/ethsettings

export iscsi_modules="e1000 libcrc32c crc32c md5 scsi_transport_iscsi iscsi_sfnet"

if [ "$KERNEL" != "" ] ; then
	echo "Creating the default kernel initrd image..."
	chroot /mnt/sysimage /sbin/mkinitrd -f /boot/initrd-${KERNEL}.img $KERNEL
else
	echo "*** Error: There default kernel version could not be determined! ***"
fi

if [ "$KERNELSMP" != "" ] && [ -d /mnt/sysimage/lib/modules/${KERNELSMP} ]; then
	echo "Creating the SMP kernel initrd image..."
	chroot /mnt/sysimage /sbin/mkinitrd -f /boot/initrd-${KERNELSMP}.img $KERNELSMP
fi

if [ "$KERNELHUGEMEM" != "" ] && [ -d /mnt/sysimage/lib/modules/${KERNELHUGEMEM} ]; then
	echo "Creating the hugemem kernel initrd image..."
	chroot /mnt/sysimage /sbin/mkinitrd -f /boot/initrd-${KERNELHUGEMEM}.img $KERNELHUGEMEM 
fi

echo "Modifying network scripts..."
cp -f $SCRIPTDIR/postinstall/etc/network.iscsi /mnt/sysimage/etc/rc.d/init.d/network

echo "iSCSI booting is now correctly configured. Please reboot your system."
