#!/bin/bash -e

script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

cd $script_dir

if [[ $# -ne 2 ]]; then
    echo "Invalid number of arguments"
    echo "Usage: ./local_runner {test_suite} {test_name}"
    exit 1
fi

test_suite=$1
test_name=$2
test_path="${test_suite}/${test_name}.py"

if [ ! -f ${test_path} ]; then
    echo "Test ${test_name}.py does not exist"
    echo "Usage: ./local_runner {test_suite} {test_name}"
    exit 1
fi

NUM_MACHINES="$(cat $test_path | grep -m1 "NUM_MACHINES" | tail -c 2)"

# Define machine ips
for i in `seq 1 $NUM_MACHINES`;
do
  export "MACHINE${i}"="127.0.0.1"
done

# Run workers
for i in `seq 2 $NUM_MACHINES`;
do
    CURRENT_MACHINE="MACHINE$i" ./jail_service.py &
    pids[$i]=$!
done

quit()
{
    # Stop workers
    sleep 1
    for i in `seq 2 $NUM_MACHINES`;
    do
        kill ${pids[$i]} || true
    done
}

trap 'quit' INT

# Run master with test
args="--machines-num $NUM_MACHINES --test-suite $test_suite --test $test_name"
CURRENT_MACHINE="MACHINE1" ./master.py $args || quit

quit
