#!/bin/sh

# set the path for our tests
PATH=$PATH:/usr/local/bin:/usr/local/sbin:.

REPOS="$1"  # /svn/nsd or /svn/libdns   # get these from svn
REV="$2"                                # which revision number

SVN_BAR="------------------------------------------------------------------------"

# our environment is extremely limited we don't even
# get a LOGNAME here... this makes all the pre script
# fail in the test. We do get a pwd from svnserve
LOGNAME=`basename $PWD`
USERNAME=$LOGNAME

id $USERNAME
if [[ $1 -eq 1 ]]; then
        # no legal username
        exit 0
fi

# please edit these to suit your needs
TPKG=/home/miekg/svn/tpkg/trunk/tpkg    # tpkg version to use
MAILTO="ldns-team@nlnetlabs.nl"         # where to send the status email
NAME="ldns"                             # name of the project
MAILSUB="[svn: $NAME|$BRANCH] $REV status"       # subject of status emails
REPOPROT="file://"                      # local or remove (svn+ssh://)
TESTDIR="test"                          # dir where the tests live in the repo

# get the branch name
LOOK=`/usr/bin/svnlook changed -r$REV $REPOS | /usr/bin/awk '{ print $2 }'`
if [[ $LOOK =~ '^trunk' ]]; then
        REPOPATH="trunk"
fi
if [[ $LOOK =~ '^branches' ]]; then
        REPOPATH=`echo $LOOK | cut -f1,2 -d /`
fi
if [[ $LOOK =~ '^tags' ]]; then
        REPOPATH=`echo $LOOK | cut -f1,2 -d /`
fi

BUILD_DIR=`mktemp -d /tmp/XXXXXX`
if [ ! -d $BUILD_DIR ]; then
        exit 0
fi

START=`date +%s`
MAIL_FILE=`mktemp /tmp/XXXXXXX`

# checkout to $BUILD_DIR, assume local checkout
svn co -r$REV $REPOPROT$REPOS/$REPOPATH $BUILD_DIR
( cd $BUILD_DIR ; svn log -r$REV > $MAIL_FILE )
svnlook changed -r$REV $REPOS >> $MAIL_FILE
echo $SVN_BAR >> $MAIL_FILE

# set the path and other stuff for our sibling test scripts
echo "export PATH=$PATH" > $BUILD_DIR/$TESTDIR/.tpkg.var.master
echo "export LOGNAME=$LOGNAME" >> $BUILD_DIR/tpkg/.tpkg.var.master
echo "export USERNAME=$USERNAME" >> $BUILD_DIR/tpkg/.tpkg.var.master

###
# This should be the only thing you need to tweak
###

if [[ -d $BUILD_DIR/$TESTDIR ]]; then 

        # RUN THE TESTS
        for tests in $BUILD_DIR/$TESTDIR/*.tpkg ; do
                nice $TPKG  -b $BUILD_DIR/$TESTDIR -a $BUILD_DIR \
                exe `basename $tests` >> $MAIL_FILE
        done

        END=`date +%s`
        echo ELAPSED: $((END - START)) s >> $MAIL_FILE
        echo $SVN_BAR >> $MAIL_FILE

        # add -q to /not/ show PASSED tests
        $TPKG -b $BUILD_DIR/$TESTDIR report >> $MAIL_FILE
        $TPKG -b $BUILD_DIR/$TESTDIR clean 
        ###
        # End of tweaking
        ###
fi

# SVN STUFF
( cd $BUILD_DIR ; svn diff -rPREV:$REV >> $MAIL_FILE )

rm -rf $BUILD_DIR

cat $MAIL_FILE | mail -s "${MAILSUB}" $MAILTO
rm -f $MAIL_FILE
