#!/bin/sh

# Start the DBT-2 Driver.

usage()
{
	echo "usage: $0 <client address> [WAREHOUSES [DURATION [WAREHOUSE_MIN [WAREHOUSE_MAX]]]]"
}

# Use the specified engine from the environment, or try podman then docker.
if [ "$ENGINE" = "" ]; then
	ENGINE="podman"
	if ! which $ENGINE > /dev/null 2>&1; then
		ENGINE="docker"
		if ! which $ENGINE > /dev/null 2>&1; then
			echo "podman nor docker in path"
			exit 1
		fi
	fi
else
	if ! which $ENGINE > /dev/null 2>&1; then
		echo "specified engine $ENGINE not in path"
		exit 1
	fi
fi
echo "using container engine: $ENGINE"

if [ "$ENGINE" = "podman" ]; then
	# Sometimes it's "podman", sometimes "cni-podman0".
	PODMANNETWORK=$(podman network ls -q | grep podman | head -n 1)
	echo "using podman network: $PODMANNETWORK"
	ENGINEARGS="--network=$PODMANNETWORK"
fi

if [ $# -lt 1 ]; then
	usage
	exit 1
fi

CONTAINER_NAME="dbt2-driver-${WAREHOUSES}w"
CONTAINER_TAG="dbt2-driver"
WAREHOUSES=1
WMIN=1
WMAX=1
# In seconds.
TEST_LENGTH=120

HOST=$1

if [ $# -ge 2 ]; then
	WAREHOUSES=$2
	WMAX=$WAREHOUSES
fi

if [ $# -ge 3 ]; then
	TEST_LENGTH=$3
fi

if [ $# -ge 4 ]; then
	WMIN=$4
fi

if [ $# -ge 5 ]; then
	WMAX=$5
fi

CONTAINERDIR=$(dirname "$0")

# Use the return code from `$ENGINE inspect` to determine if the container
# image needs to be created.
$ENGINE inspect $CONTAINER_TAG > /dev/null
if [ $? -ne 0 ]; then
	"${CONTAINERDIR}/build-driver" || exit 1
fi

if [ ! "x$VERBOSE" = "x1" ]; then
	VERBOSE=0
fi

if [ ! "x$VERSION" = "x2" ]; then
	VERSION=""
fi

NO_THINK_TIME="-ktd 0 -ktn 0 -kto 0 -ktp 0 -kts 0 -ttd 0 -ttn 0 -tto 0 -ttp 0 -tts 0"
$ENGINE run \
		$ENGINEARGS \
		--rm \
		--name "$CONTAINER_NAME" \
		$CONTAINER_TAG \
		bash -c "dbt2-driver${VERSION} -d $HOST -wmin $WMIN -wmax $WMAX -w $WAREHOUSES -l $TEST_LENGTH $NO_THINK_TIME -sleep 100 -outdir /tmp && if [ "x$VERSION" = "x2" ]; then cat /tmp/mix-*.log > /tmp/mix.log; fi &&  VERBOSE=${VERBOSE} dbt2-post-process /tmp/mix.log"
if [ $? -ne 0 ]; then
	usage
	exit 1
fi
