#!/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) Yugabyte database builder.

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

Options:
  -l PORT        YugabyteDB 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
  -s TYPE        user defined functions TYPE to install 'c' or 'plpgsql',
                 default: plpgsql
  -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
UDF_TYPE="plpgsql"
while [ "${#}" -gt 0 ] ; do
	case "${1}" in
	(-l)
		shift
		PORT="${1}"
		;;
	(-r)
		REBUILD_DB=1
		;;
	(-s)
		shift
		UDF_TYPE="${1}"
		;;
	(-w)
		shift
		WAREHOUSES="${1}"
		;;
	(-\? | --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 ] && [ -d $DBT2PGDATA ]; then
	dbt2 pgsql-drop-db "${PORTARG}"
fi

dbt2 pgsql-create-db "${PORTARG}" || exit 1
dbt2 pgsql-create-tables "${PORTARG}" "${TABLESPACES_FLAG}" || 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}"

dbt2 yugabyte-load-db "${PORTARG}" -s "${SEED}" -w "${WAREHOUSES}" || exit 1
dbt2 pgsql-create-indexes "${PORTARG}" "${TABLESPACES_FLAG}" || exit 1
dbt2 pgsql-load-stored-procs "${PORTARG}" -t "${UDF_TYPE}" || exit 1

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

SEED=$(dbt2 rand -1 1 15)
psql "${PORTARG}" -e -d "${DBT2DBNAME}" -c "SELECT setseed(${SEED});" || exit 1

exit 0
