#!/bin/bash
set -xe

target="${1:-networks/basic}"
cd "$(git rev-parse --show-toplevel)"

if [ -z "${CHUTNEY_PATH}" ]; then
    # CHUTNEY_PATH isn't set; try cloning a local chutney.
    if [ -d chutney ]; then
	(cd ./chutney && git pull)
    else
	git clone https://gitlab.torproject.org/tpo/core/chutney
    fi
    CHUTNEY_PATH="$(pwd)/chutney"
    export CHUTNEY_PATH
else
    # CHUTNEY_PATH is set; tell the user about that.
    echo "CHUTNEY_PATH is ${CHUTNEY_PATH}; using your local copy of chutney."
fi

if [ ! -e "${CHUTNEY_PATH}/${target}" ]; then
    echo "Target network description ${CHUTNEY_PATH}/${target} not found."
    exit 1
fi

"${CHUTNEY_PATH}/chutney" configure "${CHUTNEY_PATH}/$target"
"${CHUTNEY_PATH}"/chutney start "${CHUTNEY_PATH}/$target"
CHUTNEY_START_TIME=180 "${CHUTNEY_PATH}"/chutney wait_for_bootstrap "${CHUTNEY_PATH}/$target"
"${CHUTNEY_PATH}"/chutney verify "${CHUTNEY_PATH}/$target"

if [ -x ./target/x86_64-unknown-linux-gnu/debug/arti ]; then
	cmd=./target/x86_64-unknown-linux-gnu/debug/arti
else
	cargo build
	cmd=./target/debug/arti
fi

(
	set +e
	"$cmd" proxy -c "${CHUTNEY_PATH}/net/nodes/arti.toml" &
	pid=$!
	echo "target=$target" > tests/chutney/arti.run
	echo "pid=$pid" >> tests/chutney/arti.run
	wait "$pid"
	echo "result=$?" >> tests/chutney/arti.run
) & disown

# Wait for arti to start listening (it does so "immediately", but we don't want to get there first)
# Really there should be a proper daemon startup protocol here, but arti doesn't have one yet.
for idx in $(seq 30); do
    if : >&/dev/null </dev/tcp/127.0.0.1/9150 ; then
	echo "Port 9150 seems open."
	break
    elif [ "$idx" == 30 ]; then
	echo "Waited 30 seconds without result; giving up on port 9150."
	exit 1
    else
	echo "waiting for port 9150..."
	sleep 1
    fi
done


