#! /bin/bash

# Update PATH to include path to Tclkit, otherwise cross-compiles will fail
PATH="${PATH}:/home/rkeene/bin:/usr/local/bin"
export PATH

# Define build and web paths
KITCREATORDIR="/home/rkeene/devel/kitcreator"
WEBROOTDIR="/web/rkeene/devel/kitcreator/kitbuild"
export KITCREATORDIR WEBROOTDIR

cd "${KITCREATORDIR}" || exit 1

FOSSIL_CHANGE="$(fossil timeline -n 1 -t ci | grep '^[0-9:]* \[' | sed 's@^[0-9:]* \[\([0-9a-f]*\)\].*$@\1@')"
TESTNAME="fossil_${FOSSIL_CHANGE}"
export FOSSIL_CHANGE TESTNAME

# On Wednesday, do a distclean to force redownloading everything (mainly
# for CVS Head) and force a rebuild to ensure up-to-date build status
if [ "$(date '+%u')" = "3" ]; then
	./kitcreator distclean || exit 1

	touch "${KITCREATORDIR}/build/test/force_nightly"
fi

if [ -d "${WEBROOTDIR}/${TESTNAME}" ]; then
	# Don't re-run the tests if nothing has changed
	if [ -f "${KITCREATORDIR}/build/test/force_nightly" ]; then
		rm -f "${KITCREATORDIR}/build/test/force_nightly"
	else
		exit 0
	fi
fi

cd build/test || exit 1

if [ ! -x test -o ! -x publish-tests ]; then
	echo 'Missing scripts, aborting.' >&2

	exit 1
fi

# Only run one at a time
if [ -f '__AUTO_TESTS_RUNNING__' ]; then
	exit 1
fi
touch '__AUTO_TESTS_RUNNING__'

# Clean builds
rm -rf kits

# Run tests
nice -n 20 ./test >/dev/null 2>/dev/null

# Clean old auto-generated published results
rm -rf "${WEBROOTDIR}"/svn_r*/ "${WEBROOTDIR}"/fossil_*/

# Publish New Results
./publish-tests "${TESTNAME}"

# Create nightly symlink
rm -f "${WEBROOTDIR}/nightly"
ln -s "${TESTNAME}" "${WEBROOTDIR}/nightly"

# Clean
rm -f '__AUTO_TESTS_RUNNING__'

exit 0
