
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"

hwcontext()
{
	ODIR=$1
	mkdir -p ${ODIR}/hwcontext
	cpuinfo=${ODIR}/hwcontext/cpuinfo.txt
	meminfo=${ODIR}/hwcontext/meminfo.txt

	[ -f ${cpuinfo} ] || cat /proc/cpuinfo > ${cpuinfo}
	[ -f ${meminfo} ] || cat /proc/meminfo > ${meminfo}
}

swcontext()
{
	ODIR=$1
	mkdir -p ${ODIR}/swcontext
	build=${ODIR}/swcontext/build.txt
	pkgs=${ODIR}/swcontext/pkgs.txt

	[ -f ${build} ] || getprop ro.build.display.id > ${build}
	[ -f ${pkgs} ] || pm list packages > ${pkgs}
}

cleanup()
{
	# just adds a little handy debugging
	ls ${RESULTSDIR}
	echo "${PREFIX} calling sync on device"
	sync
	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}
		mkdir ${odir}/attachments/

		touch ${odir}/stdout.log

		cp ${line}/testdef.yaml ${odir}/
		cp ${line}/testdef_metadata ${odir}/
		cp ${line}/uuid ${odir}/analyzer_assigned_uuid

		cp ${line}/run.sh ${odir}/attachments/
		echo 'text/plain' > ${odir}/attachments/run.sh.mimetype
		if [ -f ${line}/install.sh ]; then
			cp ${line}/install.sh ${odir}/attachments/
			echo 'text/plain' > ${odir}/attachments/install.sh.mimetype
			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"
				hwcontext ${odir}
				swcontext ${odir}
				continue
			fi
		fi

		echo "${PREFIX} save hardware/software context info..."
		hwcontext ${odir}
		swcontext ${odir}

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

