#!/bin/sh

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

if [ "$1" = "--continue" ]; then
    CONTINUE_FLAG=1
    shift
else
    CONTINUE_FLAG=0
fi
ORIG_DIR="$1"
REV_NUMBER=$2

if [ -f "$SAVE_DIR/dvm-tester.config" ]; then
    . "$SAVE_DIR/dvm-tester.config"
fi

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

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

FULL_REP_URL="$PUBL_BASE_URL/r${REV_NUMBER}${PUBL_SUFFIX}/"

TEST_SUITE=$(cd "$TEST_SUITE" && pwd)

# Actually, can be taken any temporary name
RESULTS_DIR="$ORIG_DIR.results"
export TMPDIR="$ORIG_DIR.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 [ $CONTINUE_FLAG -eq 0 ]; then
    rm -rf "$RESULTS_DIR"
fi
mkdir -p "$RESULTS_DIR"
cd "$SAVE_DIR"
"$MY_DIR/task-processor.sh" "$RESULTS_DIR" <"$TASK_FIFO" &

# Build DVM-systems for given platforms and sequentially feed task processor from our test-suite
exec 4>"$TASK_FIFO"
for platf in $PLATFORMS; do
    WORK_DIR="$ORIG_DIR.$platf"
    if [ $CONTINUE_FLAG -eq 0 ]; then
        rm -rf "$WORK_DIR"
    fi
    if [ ! -e "$WORK_DIR" ]; then
        cp -r "$ORIG_DIR" "$WORK_DIR"
    fi
    cd "$WORK_DIR/dvm_sys"
    if [ ! -f platforms/$platf ]; then
        if [ -f "$SAVE_DIR/$platf" ]; then
            cp "$SAVE_DIR/$platf" platforms/
        else
            echo "Can not find platform $platf"
        fi
    fi
    if [ -f platforms/$platf ]; then
        PLATFORM=$platf ./dvminstall >install.log 2>& 1
        INST_RES=$?
        if [ $INST_RES -ne 0 -o ! -f user/dvm ]; then
            :
            # TODO: Handle errors with building DVM-system
        else
            cd "$SAVE_DIR"
            "$MY_DIR/perform-tests.sh" "$WORK_DIR/dvm_sys" "$TEST_SUITE" 4
        fi
    fi
done
exec 4>&-

# Wait for task processor to finish
wait

# Cleanup stuff
rm "$TASK_FIFO"
for platf in $PLATFORMS; do
    WORK_DIR="$ORIG_DIR.$platf"
#    rm -rf "$WORK_DIR"
done

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

# Publish the report and send summary e-mail
if [ "$POPULATE_FLAG" = "1" ]; then
    cd "$SAVE_DIR"
    "$MY_DIR/populate-report.sh" "$RESULTS_DIR" "$REV_NUMBER"
fi

# Cleanup stuff finally
#rm -rf "$RESULTS_DIR"
#rm -rf "$TMPDIR"
