#!/bin/bash
#
# This script expects to be started by a Buildbot slave with PWD set to the build 
# directory.

# Script Setup
# ============

program=${0##*/}
progdir=${0%/*}
build=$PWD

. $progdir/shell-utils

# Patch Django
# ============
#
# Assuming we check out trunk or branch-XXX with the command
#	'svn co URL/BRANCH/'
# then this script will be $PWD/test/patch-django and we will place our patched
# django in $PWD/test/lib/django
#

say "Setting up a local Django for the test suite"
cd $build

django=$(py_module_path "django")
rsync -a $django $build/test/lib/ >&2

cd $build/test/lib
for patch in $build/test/*.patch; do
    patch -p 3 -t -N < $patch >&2
done

# Database setup
# ==============

#say "Setting up a database for the test suite"

# Project Setup
# =============
# put in place a suitable settings_local.py for our application to find.  This should
# be based on the local settings_local.py, but should add test-specific settings, and
# should set things up so that we use the patched Django, not the system's default
# Django.

say "Setting up the Django settings for the test suite"
cd $build

settings_local=$(py_module_file "settings_local")
[ "$settings_local" ] || die "No setting_local file available"

cat $settings_local test/settings_local_test.py > test/settings_local.py

# Acquire lock, to prevent running test and database update at the same time

for dir in $DBLOCK /var/lock /var/state /var/run /var/tmp; do
    [ -d $dir -a -w $dir ] && lock=$dir/ietfdb && break
done
[ "$lock" ] || die "Couldn't find a directory to keep lock in."

LOCKDIR=$lock
PIDFILE=$LOCKDIR/pid

while true; do
    if mkdir $LOCKDIR; then
	echo "$$" > $PIDFILE
	chmod a+rwx $LOCKDIR
	chmod a+rw $PIDFILE
	echo $PIDFILE			# tell caller about the pidfile
	break
    else
	pid=$(< $PIDFILE )
	[ "$pid" ] || die "Couldn't read pidfile '$PIDFILE'"
	if kill -0 $pid; then
	    say "Pidfile for process $pid exists, and process is running. Sleeping."
	    sleep 10
	else
	    say "Pidfile for process $pid exists, but process doesn't seem to be running."
	    die "Remove lockdir $LOCKDIR and old pid file $pidfile."
	fi
    fi
done


exit $warnings