#!/bin/bash

#### functions #####

function get_partitions()
{

	file=$1
	
	mount | grep "\/dev" | awk '
	BEGIN {
		boot_detected=0;
		root_pat=""
		root_fs=""
	}
	$3 ~ /^\/$/ {
		print "ROOT_PARTITION="$1;
		print "ROOT_FS="$5;
		root_pat=$1
		root_fs=$5
		next;
	}
	$3 ~ /^\/boot$/ {
		print "BOOT_PARTITION="$1;
		print "BOOT_FS="$5;
		boot_detected=1
		next;
	}
	END {
		if ( !boot_detected ) {
			print "BOOT_PARTITION="root_pat;
			print "BOOT_FS="root_fs;
		}
	}
	' >> $file

	fstab_file="/etc/fstab"
	rootdev=`awk -F "=" '$1 ~ /ROOT_PARTITION/ {print $2}' $file`
	echo $rootdev | fgrep "VolGroup" > /dev/null
	val=$?
	if [ $val -eq 1 ];then

		/sbin/fdisk -l 2> /dev/null | awk '
		$7 ~ /^swap$/ {
			print "SWAP_PARTITION="$1;
			next;
		}
		' >> $file
	else
		awk '
		$2 ~ /^swap$/ {
			print "SWAP_PARTITION="$1;
		}
		' $fstab_file >> $file
	fi
}

function get_ip()
{
	file=$1

	ip=`/sbin/ifconfig eth0 | grep "inet addr" | cut -d":" -f2  | cut -d " " -f1`
	echo "IPADDR=$ip" >> $file
}

function set_boot_loader()
{
	file=$1
	boot_loader=$2

	echo "BOOTLOADER=$boot_loader" >> $file

}

####  main #######
# This script assumes that it is called from wrapper scripts only and
# assumes arguments are correct.

BASE_PATH=$1
SYSTEM_NAME=$2
BOOT_LOADER=$3
LOG_FILE=/root/iSCSI_boot.log

KVER=`uname -r | sed 's/BOOT//' | sed 's/default//'`

if [ -d /lib/modules/$KVER\smp ]
then
	KVER=$KVER\smp
elif [ -d /lib/modules/$KVER\bigsmp ]
then
	KVER=$KVER\bigsmp
else
	if [ -f /etc/SuSE-release ]
	then
		KVER=$KVER\default
	fi
	if [ ! -d /lib/modules/$KVER ]
	then
		echo "ERROR: Unable to locate kernel source tree." >> $LOG_FILE
		echo -n "       Please select 'Kernel Development' package during" >> $LOG_FILE
		echo "       installation." >> $LOG_FILE
		exit 1
	fi
fi

echo "KVER=$KVER" > $BASE_PATH/iboot.conf
echo "DRIVER=bnx2" >> $BASE_PATH/iboot.conf

get_partitions $BASE_PATH/iboot.conf
get_ip $BASE_PATH/iboot.conf
echo "HOSTNAME=$SYSTEM_NAME" >> $BASE_PATH/iboot.conf
set_boot_loader $BASE_PATH/iboot.conf $BOOT_LOADER
exit 0

