#!/bin/sh

unset CDPATH

MY_DIR=$(cd "$(dirname "$(which "$0")")" && pwd)

POPULATE_FLAG=0
WORKING_DIR=`pwd`
REV=

parse_params() {
    while [ -n "$1" ]; do
        if [ "$1" = "--working-dir" ]; then
            WORKING_DIR="$2"
            shift
        elif [ "$1" = "--populate" ]; then
            POPULATE_FLAG=1
        else
            REV=$1
        fi
        shift
    done
}

parse_params $@

if [ -z "$REV" ]; then
    exit 1
fi

if [ -f "$WORKING_DIR/dvm-tester.config" ]; then
    . "$WORKING_DIR/dvm-tester.config"
else
    exit 1
fi

REPO_URL="$REPO_BASE_URL/dvm/releases/current-trunk"
SVN_PARAMS="--username $REPO_USER --password $REPO_PASS --non-interactive"

update_test_suite() {
    if [ -e "$TEST_SUITE/.svn" ]; then
        ( cd "$TEST_SUITE" && svn $SVN_PARAMS update )
    fi
}

test_revision() {
    REV=$1
    echo "[$(date)] Testing revision $REV"
    SAVE_DIR=`pwd`
    WORK_DIR="$WORKING_DIR/dvm_r$REV"
    rm -rf "$WORK_DIR"
    svn co $SVN_PARAMS -r $REV "$REPO_URL" "$WORK_DIR" >/dev/null
    SVN_RES=$?
    while [ $SVN_RES -ne 0 ]; do
        sleep 1
        rm -rf "$WORK_DIR"
        svn co $SVN_PARAMS -r $REV "$REPO_URL" "$WORK_DIR" >/dev/null
        SVN_RES=$?
    done
    cd "$WORK_DIR"
    TMP_FILE=`mktemp`
    svn propget svn:externals >$TMP_FILE
    SVN_RES=$?
    while [ $SVN_RES -ne 0 ]; do
        svn propget svn:externals >$TMP_FILE
        SVN_RES=$?
    done
    CHILDREN=`cat $TMP_FILE | sed '/^$/d' | awk '{print $(NF)}'`
    rm $TMP_FILE
    for d in $CHILDREN; do
        cd "$WORK_DIR/$d"
        svn up $SVN_PARAMS -r $REV >/dev/null
        SVN_RES=$?
        while [ $SVN_RES -ne 0 ]; do
            sleep 1
            svn cleanup $SVN_PARAMS
            svn up $SVN_PARAMS -r $REV >/dev/null
            SVN_RES=$?
        done
    done
    rm -rf "$WORK_DIR.tmp"
    mv "$WORK_DIR" "$WORK_DIR.tmp"
    svn export "$WORK_DIR.tmp" "$WORK_DIR" >/dev/null
    SVN_RES=$?
    while [ $SVN_RES -ne 0 ]; do
        sleep 1
        rm -rf "$WORK_DIR"
        svn export "$WORK_DIR.tmp" "$WORK_DIR" >/dev/null
        SVN_RES=$?
    done
    rm -rf "$WORK_DIR.tmp"
    cd "$WORKING_DIR"
    POPULATE_FLAG=$POPULATE_FLAG "$MY_DIR/build-and-test.sh" "$WORK_DIR" $REV
    echo "[$(date)] Testing revision $REV done"
#    rm -rf "$WORK_DIR"
    cd "$SAVE_DIR"
}

update_test_suite
test_revision $REV
