#!/bin/bash

function print_usage_and_exit {
    echo "./local_runner --test-suite test_suite [--distributed] [--num-machines num_machines]"
    echo "Required arguments:"
    echo -e "  --test-suite test_suite\trun test_suite scenarios, test_suite must be test folder in tck_engine/tests."
    echo -e "  --name name\tunique identifer of test_suite and its parameters"
    echo "Optional arguments:"
    echo -e "  --memgraph-params \"param1=value1 param2=value2\"\tcommand line arguments for memgraph"
    echo -e "  --distributed\trun memgraph in distributed"
    echo -e "  --num-machines num-machines\tnumber of machines for distributed, default is 3"
    exit 1
}

# exit if any subcommand returns a non-zero status
set -e

# read arguments
distributed=false
num_machines=3
memgraph_params=""
while [[ $# -gt 0 ]]; do
    case $1 in
        --distributed)
            distributed=true
            shift
            ;;
        --num-machines)
            if [ $# -eq 1 ]; then
                print_usage_and_exit
            fi
            num_machines=$2
            re='^[0-9]+$'
            if ! [[ $num_machines =~ $re  ]] ; then
                print_usage_and_exit
            fi
            shift
            shift
            ;;
        --memgraph-params)
            if [ $# -eq 1 ]; then
                print_usage_and_exit
            fi
            memgraph_params=$2
            shift
            shift
            ;;
        --name)
            if [ $# -eq 1 ]; then
                print_usage_and_exit
            fi
            name=$2
            shift
            shift
            ;;
        --test-suite)
            if [ $# -eq 1 ]; then
                print_usage_and_exit
            fi
            test_suite=$2
            shift
            shift
            ;;
        *)
            # unknown option
            print_usage_and_exit
            ;;
    esac
done

if [[ "$test_suite" = "" ]]; then
    print_usage_and_exit
fi

# save the path where this script is
script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# activate virtualenv
source $script_dir/ve3/bin/activate

# run scenarios
cd ${script_dir}
tck_flags="--root tck_engine/tests/$test_suite
           --test-name $name
           --db memgraph"

if [[ $distributed = true ]]; then
    tck_flags="$tck_flags --distributed"
    tck_flags="$tck_flags --num-machines $num_machines"
fi

if [ -n "$memgraph_params" ]; then
    python3 tck_engine/test_executor.py $tck_flags --memgraph-params \"$memgraph_params\"
else
    python3 tck_engine/test_executor.py $tck_flags
fi