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

while getopts "l:" OPT; do
	case ${OPT} in
	l)
		PORT=${OPTARG}
		;;
	esac
done

if [ ! "x${PORT}" = "x" ]; then
    PORTOPT="-p ${PORT}"
fi
PSQL="psql -X ${PORTOPT} -d ${DBT2DBNAME} -At"

# Create database
echo "Creating database..."

SQL="SELECT 1 FROM pg_database WHERE lower(datname) = lower('${DBT2DBNAME}');"

RC=$(eval "${PSQL} -c \"${SQL}\" 2> /dev/null")

if [ "${RC}" = "1" ]; then
	echo "database already exists: ${DBT2DBNAME}"
else
	eval "createdb ${PORTOPT} ${DBT2DBNAME}" || exit 1
fi

exit 0
