#!/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
#

if [ -z ${DBT2DBNAME} ]; then
	echo "DBT2DBNAME not defined."
	exit 1
fi

usage()
{
	echo "Usage:"
	echo "    `basename $0` [options]"
	echo "    `basename $0` -h"
	echo "Options:"
	echo "    -l <PORT>"
	echo "        PostgreSQL port"
	echo "    -r <RATE>"
	echo "        How many warehouses to commit at a time, default: $RATE"
	echo "    -s <SEED>"
	echo "        User defined functions to install, default: c"
	echo "    -w <WAREHOUSES>"
	echo "        Number of warehouses to build. Default 1."
}

RATE=100
SEED=""
WAREHOUSES=1
while getopts "hl:r:s:w:" OPT; do
	case ${OPT} in
	h)
		usage
		exit 0
		;;
	l)
		PORT=${OPTARG}
		;;
	s)
		SEED=$OPTARG
		;;
	w)
		WAREHOUSES=$OPTARG
		;;
	esac
done

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

PSQL="psql -X ${PORTARG} -d ${DBT2DBNAME}"

# Generate a seed randomly if one is not provided.
if [ "x${SEED}" = "x" ]; then
	SEED=$(dbt2 rand -1 1 15)
fi

load_table() {
	local TABLE=$1
	local WAREHOUSES=$2
	local SEED=$3

	# simulate ceiling function
	T=$(( ($WAREHOUSES + $RATE - 1) / $RATE ))
	P=`seq 1 ${T}`
	for i in ${P}; do
		run_datagen $T $i $TABLE $WAREHOUSES $SEED
	done
}

run_datagen()
{
	local TOTAL=$1
	local PART=$2
	local TABLE=$3
	local WAREHOUSES=$4
	local SEED=$5

	dbt2 datagen --direct -w "${WAREHOUSES}" --pgsql --table "${TABLE}" \
			--seed "${SEED}" -P "${TOTAL}" -p "${PART}"
	if [ $? -ne 0 ]; then
		echo "ERROR: datagen couldn't load part $PART of $TOTAL with $TABLE"
		exit 1
	fi
}

echo "loading up to $RATE warehouses at a time"

# Load one table at a time, but each table load will be parallelized.
for TABLE in item warehouse stock district customer history orders new_order;
do
	load_table $TABLE $WAREHOUSES $SEED
done
