#!/bin/sh

# (C) Copyright 2002-2005 Hewlett-Packard Development Company, L.P.

DetermineFilePath() {
	local rpm="$(which rpm)"
	if [ -z "$rpm" ]; then
		echo "Error: Unable to find the rpm command"
		exit 1
	fi
	RPM_SOURCEDIR="$(rpm --eval '%{_sourcedir}')"
	RPM_SPECDIR="$(rpm --eval '%{_specdir}')"
	RPM_RPMDIR="$(rpm --eval '%{_rpmdir}')"

}

CreateTarBall() {
        VERSION=`rpm -q hp-ilo|cut -f3 -d-`
	mkdir -p /opt/hp/hp-ilo/tmp/hpilo-$VERSION
        cp /opt/hp/hp-ilo/drivers/misc/*.[c,h] /opt/hp/hp-ilo/tmp/hpilo-$VERSION
        cp /opt/hp/hp-ilo/drivers/misc/Makefile /opt/hp/hp-ilo/tmp/hpilo-$VERSION
	tar -cz -C /opt/hp/hp-ilo/tmp . > $RPM_SOURCEDIR/hpilo-$VERSION.tar.gz 
} 

CreateSpecFile() {
	FLAG="custom"
	OLD_PASS=`egrep "^Release" $SPECFILE |cut -d: -f 2 |awk '{print $1}' |cut -d. -f 1 |awk '{print $1}'`
	NEW_PASS=`expr ${OLD_PASS} + 1`.$FLAG
	sed -e "s/\(Release[ \t]*:[ \t]*\)${OLD_PASS}/\1${NEW_PASS}/" < $SPECFILE > "$RPM_SPECDIR/$SPECFILE"
	popd
}


FixupModVersion() {
	pushd /opt/hp/hp-ilo/drivers/misc
	cp hpilo.c hpilo.c.ORIGINAL
	EFS_VER=`rpm  -q --specfile "$RPM_SPECDIR/$SPECFILE" --queryformat "%{VERSION}-%{RELEASE}\n" | head -n1`
	sed -e "/MODULE_VERSION/ c\
MODULE_VERSION\(\"$EFS_VER\"\)\;" hpilo.c.ORIGINAL > hpilo.c
popd
}
echo "Setting up hp-ilo sources for custom RPM"

DetermineFilePath

SPECFILE=hp-ilo.spec
KMODSPECFILE=hpilo-kmp.spec
STAGEDIR="$RPM_SOURCEDIR/"
RPMTOOL=`which rpmbuild`
if [ $? -ne 0 ]; then
	RPMTOOL=rpm
fi

CreateTarBall

#build it
$RPMTOOL -ba /opt/hp/hp-ilo/$KMODSPECFILE

RPMPROC=`rpm -q --specfile /opt/hp/hp-ilo/$KMODSPECFILE --queryformat "%{ARCH}\n" | head -n1`

RPMFILE=`ls -1t $RPM_RPMDIR/$RPMPROC/hpilo-*.$RPMPROC.rpm | grep -v debuginfo | head -n 1`
if [ ! -z "$RPMFILE" ]; then
        echo "The hpilo module will be automatically loaded after"
        echo "intalling the appropriate Kernel Module Package"
else
	echo "RPM build with $RPM_SPECDIR/$SPECFILE failed!"
	exit 1
fi
exit 0
