#!/bin/sh

stop_containers()
{
	$ENGINE stop dbt2-driver-0
	if [ "$DBMS" = "cockroach" ]; then
		$ENGINE stop dbt2-cockroach-1 dbt2-cockroach-2 dbt2-cockroach-3
	else
		$ENGINE stop "$CONTAINER_NAME"
	fi
}

DBMS="pgsql"
WAREHOUSES=1

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

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

if [ "$TIERS" = "" ]; then
	TIERS=2
fi

if [ ! "$TIERS" = "2" ]; then
	# A 3-tier test needs the driver to reach a client started in another
	# container, which dbt2 run currently only knows how to do over ssh.
	echo "ERROR: only TIERS=2 tests are currently supported"
	exit 1
fi

CONTAINER_DIR="$(dirname "$(realpath "${0}")")"
RESULTSNAME="${DBMS}-${WAREHOUSES}w-${TIERS}tier"
mkdir -p "${CONTAINER_DIR}/results/"
LOCALDIR="${CONTAINER_DIR}/results/${RESULTSNAME}"

if [ -d "${LOCALDIR}" ]; then
	echo "ERROR: save or remove ${LOCALDIR} before running again"
	exit 1
fi

if ! which jq > /dev/null 2>&1; then
	echo "ERROR: jq required but not found in path"
	exit 1
fi

# 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 --cap-add SYS_ADMIN"
fi

CONTAINER_TAG="dbt2-database-${DBMS}-${WAREHOUSES}w"
CONTAINER_NAME="dbt2-database-${DBMS}-${WAREHOUSES}w-0"

# Stop the containers on any exit, normal or not, once they have been
# started.  Signals route through the EXIT trap so cleanup runs exactly
# once, including on error paths that exit early.
STARTED=0

cleanup()
{
	if [ "$STARTED" -eq 1 ]; then
		stop_containers
	fi
}

trap cleanup EXIT
trap 'exit 1' INT TERM

if [ "$DBMS" = "yugabyte" ]; then
	$ENGINE start "$CONTAINER_NAME" || exit 1
elif [ "$DBMS" = "cockroach" ]; then
	# build-database starts a persistent three node cluster rather than
	# creating an image.
	$ENGINE start dbt2-cockroach-1 dbt2-cockroach-2 dbt2-cockroach-3 || \
			exit 1
	DBCONTAINER="dbt2-cockroach-1"
else
	# shellcheck disable=SC2086 # ENGINEARGS is intentionally word split
	$ENGINE run \
			$ENGINEARGS \
			-d \
			--rm \
			--name "$CONTAINER_NAME" \
			"$CONTAINER_TAG" || exit 1
fi

STARTED=1

if [ "$DBCONTAINER" = "" ]; then
	DBCONTAINER="$CONTAINER_NAME"
fi

# shellcheck disable=SC2086 # ENGINEARGS is intentionally word split
$ENGINE run \
		$ENGINEARGS \
		-d \
		--rm \
		--name "dbt2-driver-0" \
		"dbt2-driver" || exit 1

if [ "$ENGINE" = "podman" ]; then
	DBIPADDRESS=$($ENGINE inspect "$DBCONTAINER" | jq -r ".[0].NetworkSettings.Networks[\"$PODMANNETWORK\"].IPAddress")
elif [ "$ENGINE" = "docker" ]; then
	DBIPADDRESS=$($ENGINE inspect "$DBCONTAINER" | jq -r '.[0].NetworkSettings.IPAddress')
fi

echo "Database IP Address: $DBIPADDRESS"

if [ "$DBMS" = "cockroach" ]; then
	OSUSER="root"
elif [ "$DBMS" = "pgsql" ] || [ "$DBMS" = "yugabyte" ]; then
	OSUSER="postgres"
fi

echo "arbitrarily waiting 10 seconds to ensure containers finish starting..."
sleep 10

RESULTSDIR="/home/${OSUSER}/${RESULTSNAME}"

# CockroachDB and YugabyteDB speak the PostgreSQL protocol on their own
# ports.
RUNDBMS="$DBMS"
PORTARG=""
ENVARGS=""
if [ "$DBMS" = "cockroach" ]; then
	RUNDBMS="pgsql"
	PORTARG="--db-port=26257"
	ENVARGS="--env PGPORT=26257"
elif [ "$DBMS" = "yugabyte" ]; then
	RUNDBMS="pgsql"
	PORTARG="--db-port=5433"
	ENVARGS="--env PGPORT=5433"
fi

# shellcheck disable=SC2086 # ENVARGS and PORTARG are intentionally word split
if ! $ENGINE exec \
		-i \
		$ENVARGS \
		--env PGHOST="$DBIPADDRESS" \
		-u "$OSUSER" \
		dbt2-driver-0 \
		dbt2 run \
				--connection-delay=100 \
				--db-host="$DBIPADDRESS" \
				--db-name=dbt2 \
				--duration=120 \
				--warehouses="$WAREHOUSES" \
				$PORTARG \
				"$RUNDBMS" "$RESULTSDIR"; then
	echo "ERROR: test failed"
	exit 1
fi

$ENGINE exec \
		-i \
		-u "$OSUSER" \
		dbt2-driver-0 \
		dbt2-generate-report -i "$RESULTSDIR"

$ENGINE cp "dbt2-driver-0:$RESULTSDIR" "${LOCALDIR}"
