#!/bin/bash
# BEGIN_ICS_COPYRIGHT8 ****************************************
# 
# Copyright (c) 2015, Intel Corporation
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 
#     * Redistributions of source code must retain the above copyright notice,
#       this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of Intel Corporation nor the names of its contributors
#       may be used to endorse or promote products derived from this software
#       without specific prior written permission.
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# 
# END_ICS_COPYRIGHT8   ****************************************
##
## runmake
## -----------
## Perform a full build
## This is used by the weeklybuild script to provide product specific
## build operations for product's whose build is more complex
## than simply a "make stage prepfiles"
## When this is invoked, the current directory will be the TL_DIR for a
## full checkout of the product to be built
## This is also invoked by the ALL_EMB runmake, in which case the current
## directory will be Esm while TL_DIR will be ALL_EMB
##
## Usage:
##	runmake [-B 'build_config'] [-n]
##			or
##	runmake -r [-B 'build_config'] [-iCR] [-n]
##
## Arguments:
##	-B build_config	release type to build, (debug/release). default is release
##	-r		rerun the build in place without doing a new checkout/tag
##	-i		allow incremental builds by building in-place before package rpm
##	-R		skip building rpm, just leave in-place files
##	-C		don't clobber prior to the rerun
##	-n		No build.  Useful for checking build machine
##
## In addition, the following environment variables are expected to be set:
##	RELEASE_TAG, BRANCH_TAG, BUILD_TARGET, PRODUCT, RELEASE_HOME, BUILD_CONFIG 
##	The target command is expected to have already been run to set up the
##	environment for the specified target
##
##	re-run can be used for 2 situations:
##	1. re-run a failed build to correct incorrect weeklybuild arguments
##		or other non-source code related problems (out of disk space)
##	2. re-run a build for a different BUILD_TARGET_OS_VERSION while using the same
##		source code image/tag
##	If the source code needs to be corrected, a full weeklybuild should be run
##	after the correction such that the code is properly tagged.
##
## For developer builds (such as via dobuildall), the following combinations
## of the -r, -i, -C and -R options are useful
##	-r  - existing typical mode for developer builds
##			- clobbers any existing built files
##			- creates a src.rpm
##			- builds in rpmbuild tree
##			- creates a resulting binary rpm
##	-r -C - behaves same as -r above except skips the clobber
##	-r -i [-C] - incremental build mode for developer builds
##			- clobbers any existing built files (unless -C specified)
##			- builds SM code in place in source tree
##			- src rpm contains pre-built code
##			- rpmbuild ends up using pre-built code, creates binary rpm
##			After this build, the developer may do incremental sub-tree builds
##			using . Esm/setenv and then running make in the subtree
##	-r -i [-C] -R - incremental build mode for developer builds with no rpms
##			- same as -r -i [-C] except no rpms are created
##	none of these options - typical production build
##			- expects a fresh un-built checkout of code tree
##			- creates a src.rpm
##			- builds in rpmbuild tree
##			- creates a resulting binary rpm
##
## Recommended developer sequence of builds when debugging new code
## -r -i -C -R - performs the fastest full build possible, generates no rpms
##			It is recommended to omit the -C option on 1st build so the tree
##			is clobbered to be sure you start fresh.
##			iterate on this and code changes until the basic build works
##			and syntax errors and warnings are all resolved
##			For unit tests only needing a few binaries, they can also be
##			directly tested.
##			after initial attempt, if compile errors are limited to a subtree:
##				create a new bash shell, use . ./Esm/setenv and then
##				iterate on make in the subtree and code changes until compiles
## -r -i -C - performs a build to generate rpms
##			install the rpms and continue testing
##			if focused on a few executables:
##				create a new bash shell, use . ./Esm/setenv and then
##				iterate on make in the subtree and code changes and test of
##				the individual binary until works properly
## -r 		- perform a full build and generate rpms
##			install the rpms, confirm clean build, proper install and function
##
##	Since weeklybuild and target commands always set BUILD_CONFIG, this
##	script ignores BUILD_CONFIG.  As such the BuildOptions file
##	or the -B argument completely control BUILD_CONFIG for this product.

. $ICSBIN/funcs.sh

# A given release will be targeted for a specific version of ofed
# however we allow build.config to override if needed
export OFED_STACK_PREFIX=${OFED_STACK_PREFIX:-/usr/ofed-1.5.2}

# typically exported by build.config
export BUILD_WITH_STACK=${BUILD_WITH_STACK:-OPENIB}

Usage()
{
	# include "ERROR" in message so weeklybuild catches it in error log
	echo "ERROR: runmake failed" >&2
	echo "Usage: runmake [-B 'build_config'] [-n]" >&2
	echo "            OR" >&2
	echo "       runmake -r [-B 'build_config'] [-iCR] [-n]" >&2
	exit 2
}

build_config=
rerun=n
Cflag=n
inplace=n
rpm=y
args="$*"
while getopts B:riRCnS param
do
	case $param in
	r)
		rerun=y;;
	B)
		build_config="$OPTARG";;
	i)
		inplace=y;;
	R)
		rpm=n;;
	C)
		Cflag=y;;
	n)
		nflag=y;;
	?)
		Usage
	esac
done
shift $(($OPTIND -1))

if [ $# != 0 ]
then
		Usage
fi

if [ -z "$RELEASE_TAG" ]
then
	export RELEASE_TAG=`patch_engineer_version|cut -d"." -f1`
	echo "Defaulting RELEASE_TAG to $RELEASE_TAG"
	# engineers will always forget this flag, since clobber is fast
	# default to a rerun which will clobber first unless -C specified
	rerun=y
fi



# target will adjust TL_DIR to be our directory, hence it will be
# ALL_EMB/Esm when building in a ALL_EMB checkout
resetct
resetbsp
target $BUILD_TARGET

# the kernel rev is not important.  We simply use the kernel rev
# of the running kernel.  While BUILD_TARGET_OS_VERSION is needed by Makerules
# it will have no impact on what is actually built
export BUILD_TARGET_OS_VERSION=${BUILD_TARGET_OS_VERSION:-`uname -r`}
setver $BUILD_TARGET_OS_VENDOR $BUILD_TARGET_OS_VERSION

export PROJ_FILE_DIR=Esm
echo "Using PROJ_FILE_DIR=$PROJ_FILE_DIR"

if [ -z "$build_config" ]
then
	# default to release build
	export BUILD_CONFIG=release
elif [ "$build_config" != debug -a "$build_config" != release ]
then
	Usage
else
	export BUILD_CONFIG="$build_config"
fi

if [ "$BUILD_WITH_STACK" = "OPENIB" ]
then
	if [ ! -d $OFED_STACK_PREFIX ]
	then
		echo "$0: ERROR: OFED stack not found: $OFED_STACK_PREFIX" >&2
		exit 1
	fi
	echo "Stack to build for: $BUILD_WITH_STACK ($OFED_STACK_PREFIX)"
else
	echo "Stack to build for: $BUILD_WITH_STACK"
fi

if [ "$nflag" = "y" ]
then
	exit 0
fi

# Check if we need to build SRPM and start from there
if [ "$BUILD_TARGET_OS" = "VXWORKS" ]
then
	echo "Err: Wrong runmake file"
	exit 1
fi

if [ "x${RELEASE_TAG}" = "x" ]
then
	MODULEVERSION=`patch_engineer_version`
	RPM_REL=`echo ${MODULEVERSION}|cut -d"." -f1-2`
	RPM_VER=`echo ${MODULEVERSION}.999.999|cut -d"." -f3`
else
	MODULEVERSION=`patch_version ${RELEASE_TAG}`
	RPM_REL=`echo ${MODULEVERSION}|cut -d"." -f1-4`
	RPM_VER=`echo ${MODULEVERSION}.999.999.999.999|cut -d"." -f5`
fi
export MKRPM_REL=${RPM_REL}
export MKRPM_VER=${RPM_VER}`rpm --eval %{?dist}`

# even if building rpms, clobber to cleanup any previous in-place builds
# so they don't end up inside the src.rpm when not wanted
# clean up from prior build when rebuilding
if [ "$rerun" = y -a "$Cflag" != y ]
then
	# force full rebuild
	# this clobber is only necessary if we have ever built inplace
	# otherwise each rpm build will get a fresh workplace for its build
	# so to save some time, only do the clobber if needed
	#for build_config in $build_configs
	#do
		#export BUILD_CONFIG=$build_config
		#if [ -e $TL_DIR/builtinplace.$PRODUCT.$BUILD_CONFIG \
		#	-o  -e $TL_DIR/builtinclude.$PRODUCT.$BUILD_CONFIG \
		#	-o  -e $TL_DIR/builtlibs.$PRODUCT.$BUILD_CONFIG \
		#	-o  -e $TL_DIR/builtbin.$PRODUCT.$BUILD_CONFIG ]
		#then
			export REMOVE_DEPENDS=yes
			make clobber clobber_stage clobber_release
			rm -f $TL_DIR/builtinplace.$PRODUCT.$BUILD_CONFIG
		#fi
	#done
fi
clobber_arg=

rm -rf $TL_DIR/$PROJ_FILE_DIR/packaged_files $TL_DIR/$PROJ_FILE_DIR/dist_files

if [ "$inplace" = y ]
then
	#echo "Building $build_configs for allkernels for $BUILD_TARGET_OS $BUILD_TARGET ..."
	echo "Building $BUILD_CONFIG for allkernels for $BUILD_TARGET_OS $BUILD_TARGET ..."
	echo "==============================================================================="
	#for build_config in $build_configs
	#do
		## setup environment using BUILD_CONFIG
		#export BUILD_CONFIG=$build_config

		#for os_version in $os_versions
		#do
			#setver $BUILD_TARGET_OS_VENDOR $os_version
			echo > $TL_DIR/builtinplace.$PRODUCT.$BUILD_CONFIG
			./rpm_runmake -r -C -B $BUILD_CONFIG
		#done
	#done
	args="$args -r -C"	# we pre-built, so skip clobber in rpmbuild
fi

if [ "$rpm" = y ]
then
	set -x
	# Copy the spec file for editing.
	cp opa-fm.spec.base opa-fm.spec

	# Repair the spec file
	sed -i "s/^Version:.*/Version: ${RPM_REL}/g" opa-fm.spec
	sed -i "s/^Release:.*/Release: ${RPM_VER}%{?dist}/g" opa-fm.spec
	if [ -d IbAccess ] ; then 
		sed -i "s/^%doc Esm\/README/%doc README/g" opa-fm.spec; 
	fi;

	# Pass command-line arguments to rpmbuild 
	sed -i "s/^\.\/fmbuild.*/\.\/fmbuild -V \%{version}\.\%{release} $args/g" opa-fm.spec

	# update distro dependencies
	./update_opa-fm_spec.sh

	# Pass env variables to rpmbuild. In integration build,
	# Most of the rpmbuild environment variables remains the same except
	# a few (like TL_DIR). However, when the SRPM is built on another
	# different machine, the environment variables may be totally
	# different. In that case, we may want to pass (hardcode) some
	# environment variables.
	echo "# Adjust the environment variables if necessary" > build.env
	echo "export PRODUCT=${PRODUCT}" >> build.env
	echo "export RELEASE_TAG=${RELEASE_TAG}" >> build.env
	echo "export BUILD_CONFIG=\${BUILD_CONFIG:-\"${BUILD_CONFIG}\"}" >> build.env
	echo "export BUILD_WITH_STACK=${BUILD_WITH_STACK}" >> build.env

	# if in-place build left builtbin, builtinclude and builtlibs, pick them up
	# to accelerate incremental builds
	FILES_TO_TAR=
	for i in builtbin builtinclude builtlibs builtinplace
	do
		if [ -e $TL_DIR/$i.$PRODUCT.$BUILD_CONFIG ]
		then
			FILES_TO_TAR="$FILES_TO_TAR $i.$PRODUCT.$BUILD_CONFIG"
		fi
	done
	cd ../
	#rm -rf rpmbuild
	mkdir -p rpmbuild/{BUILD,RPMS,SOURCES,SPECS,SRPMS}
	# Create source tar ball. Update licenses if needed.
	if [[ "$RELEASE_TYPE" == "EMBARGOED" ]]
	then
		echo "Building Embargoed Release"
		export OPA_LICENSE_DIR=${TL_DIR}/CodeTemplates/EmbargoedNotices
		OWD=${PWD}
		TMP=$(mktemp -d)
		cp -rp * ${TMP}
		cd ${TMP}
		${TL_DIR}/CodeTemplates/update_license.sh -c -q ${TMP}
		tar -cvzf ${OWD}/rpmbuild/SOURCES/opa-fm.tar.gz -T Esm/tar_inc_srcs_all --exclude-vcs -X Esm/tar_exc_pattern $FILES_TO_TAR
		cd ${OWD}
		rm -rf ${TMP}
	else
		echo "Building Public Release"
		tar -cvzf rpmbuild/SOURCES/opa-fm.tar.gz -T Esm/tar_inc_srcs_all --exclude-vcs -X Esm/tar_exc_pattern $FILES_TO_TAR
	fi
	cp Esm/opa-fm.spec rpmbuild/SPECS/
	cd rpmbuild
	rpmbuild -ba --define "_topdir $(pwd)" SPECS/opa-fm.spec
	cd ../Esm
	make final_package

	# Remove temp files
	rm -f opafm.spec
	rm -f build.env
fi

exit 0
