#!/bin/bash

# NOTE: Ensure PARALLEL_MAKE is set in the environment whitelist:
#       BB_ENV_EXTRAWHITE
#       in scripts/oe-buildenv-internal

BB_RANGE="04 05 06 07 08 09 10 11 12 13 14 15 16"
PM_RANGE="04 05 06 07 08 09 10 11 12 13 14 15 16"

DATADIR="stats-$$"
BB_CMD="bitbake core-image-sato"
#BB_CMD="bitbake -e core-image-sato | egrep '(BB_NUMBER_THREADS|PARALLEL_MAKE)'"
#DEBUG=1
RUNTIME_LOG="$DATADIR/bb-pm-runtime.dat"

TIME_STR="%e %S %U %P %c %w %R %F %W %K %M %t %k %r %s"

if [ -e "$DATADIR" ]; then
	echo "Please move $DATADIR and run again."
	exit 1
fi

mkdir $DATADIR
if [ $? -ne 0 ]; then
	echo "Failed to create $DATADIR."
	exit 1
fi

# Add a simple header
echo "BB PM $TIME_STR" > $RUNTIME_LOG
for BB in $BB_RANGE; do
	for PM in $PM_RANGE; do
		if [ -n "$DEBUG" ]; then
			mkdir -p tmp/buildstats &> /dev/null
			touch pseudodone &> /dev/null
			mkdir sstate-cache &> /dev/null
			mkdir tmp-eglibc &> /dev/null
		fi
		RUNDIR="$DATADIR/$BB-$PM-build"
		mkdir $RUNDIR
		BB_LOG=$RUNDIR/$BB-$PM-bitbake.log
		date
		echo "BB=$BB PM=$PM Logging to $BB_LOG"

		# Export the variables under test and run the bitbake command
		export BB_NUMBER_THREADS="${BB##*0}"
		export PARALLEL_MAKE="-j ${PM##*0}"
		/usr/bin/time -f "$BB $PM $TIME_STR" -a -o $RUNTIME_LOG $BB_CMD &> $BB_LOG
		
		echo "  $(tail -n1 $RUNTIME_LOG)"
		echo -n "  Cleaning up..."
		mv tmp/buildstats $RUNDIR/$BB-$PM-buildstats
		rm -f pseudodone &> /dev/null
		rm -rf tmp &> /dev/null
		rm -rf sstate-cache &> /dev/null
		rm -rf tmp-eglibc &> /dev/null
		echo "done"
	done
done
