#!/bin/sh

unset CDPATH

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

DVMSYS_DIR=
if [ -f ./dvm ]; then
    DVMSYS_DIR_CMD="DVMSYS_DIR=$(grep 'dvmdir=' <./dvm | sed -s 's/export //g' | sed -s 's/dvmdir=//g')"
    eval $DVMSYS_DIR_CMD
fi
TEST_SUITE=test-suite
RESULTS_DIR=
APPEND_RESULTS=0

parse_params() {
    while [ -n "$1" ]; do
        if [ "$1" = "--dvm_sys" ]; then
            DVMSYS_DIR="$2"
            shift
        elif [ "$1" = "--test-suite" ]; then
            TEST_SUITE="$2"
            shift
        elif [ "$1" = "--append-results" ]; then
            APPEND_RESULTS=1
            RESULTS_DIR="$2"
            shift
        else
            echo "Unknown option '$1'"
            exit 1
        fi
        shift
    done
}

parse_params $@ || exit 1

# Check settings
cd "$SAVE_DIR"
if [ ! -d "$DVMSYS_DIR" -o ! -d "$DVMSYS_DIR/user" -o ! -f "$DVMSYS_DIR/user/dvm" -o ! -d "$TEST_SUITE" ]; then
    MY_NAME=`basename "$0"`
    echo "Usage: $0 [<options>]"
    echo "    --dvm_sys     Directory of already installed DVM-system. Note that it is a directory, which contains directory 'user' directly. Usually it is .../dvm_current/dvm_sys. By default $MY_NAME searches for 'dvm' file in current directory and makes attempt to use its DVM-system"
    echo "    --test-suite  Directory with test suite, which is formed in special way. By default 'test-suite' directory is used."
    echo "    --append-results  Directory with partial results, which will be appended. By default new directory will be created."
    echo "Exiting"
    exit 1
fi

# Make them global paths
DVMSYS_DIR=$(cd "$DVMSYS_DIR" && pwd)
TEST_SUITE=$(cd "$TEST_SUITE" && pwd)

if [ $APPEND_RESULTS -eq 0 ]; then
    RESULTS_DIR="$SAVE_DIR/$(basename "$TEST_SUITE").results"
else
    RESULTS_DIR=$(cd "$RESULTS_DIR" && pwd)
fi
export TMPDIR="$SAVE_DIR/$(basename "$TEST_SUITE").work"
if [ -d "/home/scratch" ]; then
    TEMPL_NAME="/home/scratch/$(basename "$TMPDIR").XXX"
    TMPDIR=$(mktemp -d "$TEMPL_NAME")
fi
mkdir -p "$TMPDIR"

# Launch task processor
TASK_FIFO="$(mktemp -u).task-fifo"
mkfifo "$TASK_FIFO"
if [ $APPEND_RESULTS -eq 0 ]; then
    if [ -e "$RESULTS_DIR" ]; then
        echo -n "$RESULTS_DIR already exists. Do you want to rewrite it (Y/n)? "
        ans=n
        read ans
        if [ "$ans" != "y" -a "$ans" != "Y" ]; then
            echo "Exiting"
            exit 1
        fi
    fi
    rm -rf "$RESULTS_DIR"
fi
mkdir -p "$RESULTS_DIR"
cd "$SAVE_DIR"
"$MY_DIR/task-processor.sh" "$RESULTS_DIR" <"$TASK_FIFO" &

# Sequentially feed task processor from our test-suite
exec 4>"$TASK_FIFO"
cd "$SAVE_DIR"
"$MY_DIR/perform-tests.sh" "$DVMSYS_DIR" "$TEST_SUITE" 4
exec 4>&-

# Wait for task processor to finish
wait

# Cleanup stuff
rm "$TASK_FIFO"

# Generate final report
cd "$SAVE_DIR"
"$MY_DIR/gen-report.sh" "$TEST_SUITE" "$RESULTS_DIR"

echo "Results can be seen in $RESULTS_DIR directory"
rm -rf "$TMPDIR"
