#!/bin/bash
# Benchmark a number of kernel builds
###SHELLPACK preamble kernbench 4.4
ITERATIONS=5

###SHELLPACK parseargBegin
###SHELLPACK parseargInstall
###SHELLPACK parseargParam	--min-threads	KERNBENCH_MIN_THREADS
###SHELLPACK parseargParam	--max-threads	KERNBENCH_MAX_THREADS
###SHELLPACK parseargParam	--iterations	KERNBENCH_ITERATIONS
###SHELLPACK parseargEnd

###SHELLPACK monitor_hooks

WEB_LOCATION=https://www.kernel.org/pub/linux/kernel/v4.x/linux-${VERSION}.tar.gz
MIRROR_LOCATION=$WEBROOT/kernbench/linux-$VERSION.tar.gz
THREADS=$(($NUMCPUS))

###SHELLPACK init_only_start
pushd $SHELLPACK_DATA > /dev/null
rm -f ./linux-$VERSION.tar.gz
sources_fetch $WEB_LOCATION $MIRROR_LOCATION ./linux-$VERSION.tar.gz
tar xf linux-$VERSION.tar.gz || die Failed to extract
cd linux-$VERSION || die Unexpected layout
###SHELLPACK init_only_end

# Configure
cd $SHELLPACK_DATA/linux-$VERSION
yes '' | make defconfig > /dev/null 2>&1 || die Failed to make defconfig
make -j$THREADS clean > /dev/null

if [ "`uname -m`" = "aarch64" ]; then
	echo Removing broken entry from aarch64 defconfig
	sed -i -e '/CONFIG_CRYPTO_CRC32_ARM64/d' .config
	echo "# CONFIG_CRYPTO_CRC32_ARM64 is not set" >> .config
	yes '' | make oldconfig
fi

echo Warming run
make -j$THREADS vmlinux > /dev/null 2>&1 || die Failed to build vmlinux
make clean >/dev/null

# Build pass
###SHELLPACK threads_powertwo_begin $KERNBENCH_MIN_THREADS $KERNBENCH_MAX_THREADS $KERNBENCH_ITERATIONS
	monitor_pre_hook $LOGDIR_RESULTS $NR_THREADS
	###SHELLPACK iteration_begin $KERNBENCH_ITERATIONS
		echo Starting threads $NR_THREADS/$KERNBENCH_MAX_THREADS iteration $ITERATION/$KERNBENCH_ITERATIONS
		sync

		save_rc $TIME_CMD make -j$NR_THREADS vmlinux 2>> $LOGDIR_RESULTS/kernbench-${NR_THREADS}-$ITERATION.time > /dev/null
		grep elapsed $LOGDIR_RESULTS/kernbench-${NR_THREADS}-$ITERATION.time``
		recover_rc
		if [ $? -ne 0 ]; then
			die Failed to run kernbench
		fi

		# cleanup
		make clean >/dev/null
	###SHELLPACK iteration_end $ITERATIONS
	monitor_post_hook $LOGDIR_RESULTS $NR_THREADS
###SHELLPACK threads_powertwo_end

# Cleanup
rm -rf $SHELLPACK_DATA/*

# clean up the tree to save space
popd > /dev/null
rm -rf $TMPDIR/kernbench

exit $SHELLPACK_SUCCESS
