#!/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 ${DBT2PGDATA} ]; then
	echo "DBT2PGDATA not defined."
	exit 1
fi

if [ ! -d $DBT2PGDATA ]; then
	echo "Postgres instance does not exist at $DBT2PGDATA, run dbt2-build-db"
	exit 1
fi

LOGFILE="dbt2.log"
OUTDIR="."
while getopts "fo:p:" OPT; do
	case ${OPT} in
	f)
		rm -f ${DBT2PGDATA}/postmaster.pid
		;;
	o)
		OUTDIR=${OPTARG}
		;;
	p)
		PARAMETERS=${OPTARG}
		;;
	esac
done

if [ -f "${DBT2PGDATA}/postmaster.pid" ]; then
	echo "Database is already started: ${DBT2PGDATA}/postmaster.pid."
	exit 0
fi

if [ "x${PARAMETERS}" = "x" ]; then
	pg_ctl -D ${DBT2PGDATA} -w -l ${OUTDIR}/${LOGFILE} start
else
	pg_ctl -D ${DBT2PGDATA} -w -o "${PARAMETERS}" -l ${OUTDIR}/${LOGFILE} start
fi

if [ ! -f "${DBT2PGDATA}/postmaster.pid" ]; then
	echo "database did not start correctly, check database log"
	exit 1
fi

exit 0
