#!/bin/sh

#
# This file is released under the terms of the Artistic License.
# Please see the file LICENSE, included in this package, for details.
#
# Copyright The DBT-2 Authors
#

usage()
{
	cat << EOF
$(basename "${0}") is the Database Test 2 (DBT-2) CockroachDB database builder.

Usage:
  $(basename "${0}") [OPTION]

Options:
  -l PORT        CockroachDB PORT
  -r             drop existing database before building a new database
  --rows-per-commit ROWS
                 number of ROWS to load per transaction, default is to load all
                 data in a single transaction
  -w WAREHOUSES  number of WAREHOUSES to build, default: 1
  -?, --help     show this help, then exit

Database Test 2 (DBT-2) project page: https://github.com/osdldbt/dbt2
EOF
}

WAREHOUSES=1
REBUILD_DB=0
while [ "${#}" -gt 0 ] ; do
	case "${1}" in
	(-l)
		shift
		PORT="${1}"
		;;
	(--rows-per-commit)
		shift
		ROWS_PER_COMMIT="${1}"
		;;
	(--rows-per-commit=?*)
		ROWS_PER_COMMIT="${1#*--rows-per-commit=}"
		;;
	(-r)
		REBUILD_DB=1
		;;
	(-w)
		shift
		WAREHOUSES=${1}
		;;
	(-w?*)
		WAREHOUSES=${1#*-w}
		;;
	(-\? | --help)
		usage
		exit 0
		;;
	(--* | -*)
		echo "$(basename "${0}"): invalid option -- '${1}'"
		echo "try \"$(basename "${0}") --help\" for more information."
		exit 1
		;;
	(*)
		break
		;;
	esac
	shift
done

if [ ! "x${PORT}" = "x" ]; then
	PORTARG="-l ${PORT}"
fi

if [ $REBUILD_DB -eq 1 ]; then
	dbt2 pgsql-drop-db "${PORTARG}"
fi

if [ "${ROWS_PER_COMMIT}" -gt 0 ]; then
	LOADARGS="--rows-per-commit=${ROWS_PER_COMMIT}"
fi

dbt2 pgsql-create-db "${PORTARG}" || exit 1
dbt2 cockroach-create-tables "${PORTARG}" || exit 1

SEED=$(dbt2 rand 1 18446744073709551615 0)

# FIXME: Make datagen take argument instead of setting environment variables
# for psql.
export PGPORT="${PORT}"
export PGDATABASE="${DBT2DBNAME}"

eval dbt2 cockroach-load-db "${PORTARG}" -s "${SEED}" -w "${WAREHOUSES}" \
		"${LOADARGS}" || exit 1
dbt2 cockroach-create-indexes "${PORTARG}" || exit 1

exit 0
