#! /bin/sh

set -e

if [ -d root-tests ]
then
	echo "Deleting old test environment..."
	rm -rf root-tests
fi

echo "Installing test environment in root-tests/"
rm -rf root-tests && mkdir root-tests 2> /dev/null
rm -f config && make config config-tests install \
	     GLASNOST=glasnost-tests PORT=8500 \
	     PREFIX=`pwd`/root-tests/usr/local \
	     VARPREFIX=`pwd`/root-tests/var/lib/ \
	     ETC_DIR=`pwd`/root-tests/etc/glasnost-tests \
	     LOGPREFIX=`pwd`/root-tests/var/log \
	     SERVER_USER=`id -u` SERVER_GROUP=`id -u` \
	     WEB_USER=`id -u` WEB_GROUP=`id -u` &> /dev/null

mkdir -p root-tests/etc/apache
mkdir -p root-tests/var/lock
mkdir -p root-tests/var/run
mkdir -p root-tests/var/log/apache
PREFIX=`pwd`/root-tests \
	python -c "import os, sys; \
		   print sys.stdin.read().replace( \
		   	'PREFIX', os.environ['PREFIX'])" < tests/httpd.conf \
		> root-tests/etc/apache/httpd.conf

SERVERS="Dispatcher ArticlesServer AtomsServer AuthenticationServer \
	 IdentitiesServer CardsServer DataflowsServer CacheServer \
	 GroupsServer PeopleServer VirtualHostsServer SessionsServer \
	 PasswordAccountsServer NCardsServer"
echo "Starting Glasnost servers..."
for SERVER in $SERVERS
do
	root-tests/usr/local/sbin/glasnost-tests-ctl start-one $SERVER
done

echo "Starting Apache server..."
if [ -e /usr/sbin/apache ]; then
	/usr/sbin/apache -f `pwd`/root-tests/etc/apache/httpd.conf
elif [ -e /usr/sbin/apache-ssl ]; then
	/usr/sbin/apache-ssl -f `pwd`/root-tests/etc/apache/httpd.conf
fi

(cd tmp-tests && python ./tests.py)
root-tests/usr/local/sbin/glasnost-tests-ctl stop
kill `cat root-tests/var/run/apache.pid` || /bin/true

