#!/bin/bash

PKG=bnx2
ARCH=`uname -i`

RPM="/bin/rpm"
RPMBUILD="/usr/bin/rpmbuild"

BNX2_SPEC_FILE=bnx2.spec

if [ -f "/etc/redhat-release" ]; then
	PKG_PATH=/usr/src/redhat
else
	PKG_PATH=/usr/src/packages
	ARCH=`echo $ARCH | sed s:i386:i586:`
fi

###### function #########
function append_string()
{
	local target=$1
	local addstring=$2
	local file=$3

	awk '
        {
                if (match($0, pattern)) {
                        replacement=pattern addstring;
                        gsub(pattern, replacement, $0);
                        print $0
                } else {
                        print $0;
                }
        }' pattern=$target addstring=$addstring $file > /tmp/append.out

	mv /tmp/append.out $file

	return 0

}

##### main #####
                                                                                
if [ $# -eq 2 ]
then
        BASE_PATH=$1
	CONFIG_FILE=$2
else
        echo "usage: $0 </path/to/iboot> <config file>"
        exit 1
fi

if ! ls $BASE_PATH/srpms/$PKG* > /dev/null 2>&1
then
	echo "Error: Could not find $PKG driver source rpm under $BASE_PATH/srpms."
	exit 1
fi

BNX2_SRC_RPM=`ls $BASE_PATH/srpms/$PKG* | awk 'BEGIN{ FS="/"} {print $NF}'`
VERSION=`echo $BNX2_SRC_RPM |  awk 'BEGIN{FS="-"} {print $2}'`
BNX2_BIN_RPM=$PKG-$VERSION-1.$ARCH.rpm

if [ ! -f $CONFIG_FILE ]
then
	echo "Error: $CONFIG_FILE: file not found."
	exit 1
fi

echo "Installing bnx2 source rpm..."
${RPM} -ivh $BASE_PATH/srpms/$BNX2_SRC_RPM

if [ $? -ne 0 ]
then
	echo "Error: Failed to install bnx2 source rpm"
	exit 1
fi

. $CONFIG_FILE

echo "Building bnx2 binary rpm..."
${RPMBUILD} -bb $PKG_PATH/SPECS/$BNX2_SPEC_FILE --define "KVER $KVER"

if [ $? -ne 0 ]
then
	echo "Error: RPM build failed for bnx2"
	exit 1
fi

echo "Installing bnx2 binary rpm..."
${RPM} -ivh --force $PKG_PATH/RPMS/$ARCH/$BNX2_BIN_RPM


