#!/bin/sh

unset CDPATH

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

MAX_INVOCATIONS=-1
WAIT_INTERVAL=60
WORKING_DIR=`pwd`

parse_params() {
    while [ -n "$1" ]; do
        if [ "$1" = "--once" ]; then
            MAX_INVOCATIONS=1
        elif [ "$1" = "--max-invocations" ]; then
            MAX_INVOCATIONS=$2
            shift
        elif [ "$1" = "--working-dir" ]; then
            WORKING_DIR="$2"
            shift
        elif [ "$1" = "--wait-interval" ]; then
            WAIT_INTERVAL=$2
            shift
        fi
        shift
    done
}

parse_params "$@"

if [ -f "$WORKING_DIR/dvm-tester.config" ]; then
    . "$WORKING_DIR/dvm-tester.config"
else
    echo "No dvm-tester.config found!" >& 2
    exit 1
fi

if [ $MAX_INVOCATIONS -lt 0 ]; then
    INF_MODE=1
else
    INF_MODE=0
fi

counter=0
while [ $INF_MODE -ne 0 -o $counter -lt $MAX_INVOCATIONS ]; do
    while true; do
        if [ -f "$WORKING_DIR/dvm-tester.pause" ] && [ -n "$(cat "$WORKING_DIR/dvm-tester.pause")" ]; then
            echo "[$(date)] Paused explicitly (local)"
        elif [ -f "$MY_DIR/dvm-tester.pause" ] && [ -n "$(cat "$MY_DIR/dvm-tester.pause")" ]; then
            echo "[$(date)] Paused explicitly (global)"
        elif [ $(ps aux | grep task-processor.sh | wc -l) -gt 1 ]; then
            echo "[$(date)] Waiting existing task-processor.sh process to finish"
        else
            break
        fi
        sleep $WAIT_INTERVAL
    done
    echo "[$(date)] Attempting to get pending revision number"
    REV=`ssh $LIST_SERVER "head -n 1 $LIST_PATH && tail -n +2 $LIST_PATH >$LIST_PATH.tmp && mv $LIST_PATH.tmp $LIST_PATH"`
    echo "[$(date)] Got '$REV'"
    if [ -z "$REV" ]; then
        if [ $INF_MODE -ne 0 ]; then
            sleep $WAIT_INTERVAL
            continue
        else
            break
        fi
    fi
    "$MY_DIR/test-revision.sh" --working-dir "$WORKING_DIR" --populate $REV
    counter=$(( counter + 1 ))
done

echo "[$(date)] Exiting normally"
