
LCK=${LCK-"/lava-test-runner.lck"}

#make sure we are only run once
if [ ! -f ${LCK} ] ; then
	( flock -n 9 || exit 1 ; true ) 9>${LCK}
else
	exit 0
fi

if [ "$1" = "" ]
then
    LAVA_PATH="/data/lava"
else
	LAVA_PATH=$1
fi

echo $LAVA_PATH
PREFIX="<LAVA_TEST_RUNNER>:"
WORKFILE="$LAVA_PATH/lava-test-runner.conf"
RESULTSDIR="$LAVA_PATH/results"
BINDIR="$LAVA_PATH/../bin"

cleanup()
{
	# just adds a little handy debugging
	ls ${RESULTSDIR}
	echo "${PREFIX} exiting lava-test-runner"
}

{
	trap cleanup INT TERM EXIT

	export PATH=${BINDIR}:${PATH}
	echo "${PREFIX} started"
	mkdir -p ${RESULTSDIR}

	echo "${PREFIX} disabling suspend and waiting for home screen ..."
	disablesuspend.sh

	# move the workfile to something timestamped and run that. This
	# prevents us from running the same thing again after a reboot
	TS=`date +%s`
	mv ${WORKFILE} ${WORKFILE}-${TS}
	WORKFILE=${WORKFILE}-${TS}

	echo "${PREFIX} looking for work in ${WORKFILE}"
	for line in $(cat ${WORKFILE}); do
		# we don't have "basename" on android, but this does the
		# equivalent under mksh
		testdir=${line%/} # trim off trailing slash iff it exists
		test=${testdir/*\//}
		echo "${PREFIX} running ${test} under lava-test-shell..."
		odir=${RESULTSDIR}/${test}-`date +%s`
		mkdir ${odir}
		cp ${line}/testdef.yaml ${odir}/
		cp ${line}/testdef_metadata ${odir}/

		if [ -f ${line}/install.sh ]; then
			echo "${PREFIX} running ${test} installer ..."
			/system/bin/sh ${line}/install.sh
			R=$?
			echo ${R} > ${odir}/install_return_code
			if [ ${R} -ne 0 ] ; then
				echo "${PREFIX} ${test} installer failed, skippig"
				continue
			fi
		fi

		lava-test-shell --output_dir ${odir} /system/bin/sh -e "${line}/run.sh"
		echo "${PREFIX} ${test} exited with: `cat ${odir}/return_code`"
	done
}
