#!/bin/bash
# usage: ./buildit [-l]
#
# This script will build the Ibanez drivers.  The path to the script needs
# to be part of the invocation (e.g., ./buildit or build/buildit).  If the
# -l option is used, output will be displayed on the standard output.
# Errors and warnings are always saved in the build.log file.
#

# The location of the kernel header files can be overriden by setting KERNEL_PATH in the environment
KERNEL_PATH=${KERNEL_PATH:-/lib/modules/`uname -r`/build}
BUILDIT_DIR=`pwd`/${0%/buildit}
MODULE_DIR=$BUILDIT_DIR/..
export MODULE_DIR
CC="ccache gcc"
OPTIONS="-j 5 -C $KERNEL_PATH LSI_FW_FLASH=1 M=$MODULE_DIR V=1 FLAVOR=`uname -r`"
BUILD_LOG=$MODULE_DIR/build.log

# build(module_name, make_options, exit_code)
function build () {
	echo "BUILDIT_DIR = ${BUILDIT_DIR} MODULE_DIR= ${MODULE_DIR} COMPAT_DIR=${COMPAT_DIR}" | tee -a $BUILD_LOG
	echo Making the $1.ko kernel module | tee -a $BUILD_LOG
	set -o pipefail
	echo make $OPTIONS $2 | tee -a $BUILD_LOG
	make $OPTIONS $2 2>&1 | tee -a $BUILD_LOG
	if [ $? -eq 0 ] ; then
	      grep -q 'undefined!' $BUILD_LOG
	      if [ $? -eq 0 ] ; then
		      echo $1 has an undefined identifier. | tee -a $BUILD_LOG
		      grep 'undefined!' $BUILD_LOG
		      die "$1" "$3"
	      fi
	      echo $1 build: Passed | tee -a $BUILD_LOG
	else
	      die "$1" $3
	fi
}

# die(module_name, exit_code)
function die() {
	echo $1 build: Failed | tee -a $BUILD_LOG
	exit $2
}

rm -f $MODULE_DIR/build.log $MODULE_DIR/*.ko $MODULE_DIR/*.a 2> /dev/null
#build "hpsa"  "HPSA_DRIVER=1"      1
build "hpdsa" "RAIDSTACK_DRIVER=1" 2
[ -e release ] || mkdir release
[ -f lib.a ] && mv lib.a release
[ -f hpdsa.ko ] && strip -g hpdsa.ko
exit 0
