#!/bin/bash

usage() {
    cat <<EOF
Usage: ./psij-ci-run [--help] [--repeat]
    --help          Displays this message
    --repeat        If specified, run tests every 24 hours in a loop.
EOF
}

failifempty() {
    if [ "$2" == "" ]; then
        echo "Missing parameter for $1"
        usage
        exit 1
    fi
}

if [ -f psij-ci-env ]; then
    source psij-ci-env
fi

REPEAT=0
RESCHEDULE=0

while [ "$1" != "" ]; do
    case "$1" in
        --help)
            usage
            exit 0
            ;;
        --repeat)
            REPEAT=1
            shift
            ;;
        --reschedule)
            RESCHEDULE=1
            TIME="$2"
            shift 2
            ;;
        *)
            echo "Unrecognized command line option: $1."
            usage
            exit 1
    esac
done

if python --version 2>&1 | egrep -q 'Python 3\..*' >/dev/null 2>&1 ; then
    PYTHON="python"
else
    PYTHON="python3"
fi

# Ensure latest test runner is there
git fetch https://github.com/ExaWorks/psij-python.git
git checkout FETCH_HEAD -- tests/ci_runner.py


if [ "$REPEAT" == "1" ]; then
    CRT_TIME=`date +%s`
    while true ; do
        echo "`date` Running tests..."
        $PYTHON tests/ci_runner.py $MODE
        echo "`date` Waiting (CTRL+C to interrupt)..."
        CRT_TIME=$((CRT_TIME + 86400))
        NOW=`date +%s`
        TO_SLEEP=$((CRT_TIME - NOW))
        sleep $TO_SLEEP
    done
elif [ "$RESCHEDULE" == "1" ]; then
    CMD="./psij-ci-run --reschedule $TIME >> testing.log 2>&1"
    echo "$CMD" | at $TIME
    $PYTHON tests/ci_runner.py $MODE
else
    $PYTHON tests/ci_runner.py $MODE
fi
