#!/bin/sh

# Start the DBT-2 client.

usage()
{
	echo "usage: $0 <database address> [DBMS [CONNECTIONS]]"
}

# 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

DATABASE_CONNECTIONS=10
DBMS="pgsql"

HOST=$1

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

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

CONTAINERDIR=$(dirname $0)
CONTAINER_NAME="dbt2-client-${DATABASE_CONNECTIONS}"
CONTAINER_TAG="dbt2-client"

DBNAME="dbt2"

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

if [ "x$DBMS" = "xpgsql" ]; then
	$ENGINE run \
		$ENGINEARGS \
		-d \
		--rm \
		--name "$CONTAINER_NAME" \
		-p 30000:30000 \
		-e PGUSER="postgres" \
		$CONTAINER_TAG \
		dbt2-client -a $DBMS -f -c $DATABASE_CONNECTIONS -d $HOST -b $DBNAME \
				-o /tmp
	RC=$?
else
	RC=1
fi
if [ $RC -ne 0 ]; then
	usage
	exit 1
fi

which jq > /dev/null 2>&1
if [ $? -eq 0 ]; then
	if [ "$ENGINE" = "podman" ]; then
		IPADDRESS=$($ENGINE inspect "$CONTAINER_NAME" | jq -r ".[0].NetworkSettings.Networks[\"$PODMANNETWORK\"].IPAddress")
	elif [ "$ENGINE" = "docker" ]; then
		IPADDRESS=$($ENGINE inspect "$CONTAINER_NAME" | jq -r '.[0].NetworkSettings.IPAddress')
	fi
	echo "IP Address: $IPADDRESS"
	echo "${CONTAINERDIR}/start-driver $IPADDRESS"
else
	echo "Install jq for some tips the next time you run this script, or"
	echo "read the bottom of the file: $0"
fi
