#!/bin/sh
# $FreeBSD: ports/www/openacs/files/create_sampledb.sh.in,v 1.3 2007/08/02 13:10:48 mm Exp $
#
# This script prepares a sample PostgreSQL database 
# for use by OpenACS
#
PGUSER=pgsql
OPENACS_USER=openacs
OPENACS_DB=openacs
LOCALBASE=/usr/local
#
PGREP=/usr/bin/pgrep
SU=/usr/bin/su
AWK=/usr/bin/awk

CREATEUSERFLAGS="-A -d"

# Check if PostgreSQL version is >= 8.1.0
if `${LOCALBASE}/bin/postmaster -V | ${AWK} -F '[ .]' '{if ($3==8 && $4>=1) {exit 0} else {exit 1}}'`; then
	POSTGRESQL81=YES
	CREATEUSERFLAGS="-S -R -d"
fi

if ! `${PGREP} -U ${PGUSER} postgres > /dev/null`; then
	echo "You need PostgreSQL server installed and running."
	echo "After a fresh install, you need to initialize the database with:"
	echo "${LOCALBASE}/etc/rc.d/postgresql initdb"
	echo "Exiting ..."
	exit 1
fi

echo "Creating PostgreSQL user ${OPENACS_USER} ..."
${SU} -l ${PGUSER} -c "${LOCALBASE}/bin/createuser ${CREATEUSERFLAGS} ${OPENACS_USER}" 
echo "Creating PostgreSQL database ${OPENACS_DB} ..."
${SU} -l ${OPENACS_USER} -c "${LOCALBASE}/bin/createdb -E UNICODE ${OPENACS_DB}"
echo "Registering language plpgsql for database ${OPENACS_DB} ..."
${SU} -l ${PGUSER} -c "${LOCALBASE}/bin/createlang plpgsql ${OPENACS_DB}"

if [ "x${POSTGRESQL81}" = "xYES" ]; then
	echo ""
	echo "**************************** NOTICE ****************************"
	echo "You have PostgreSQL 8.1 or greater installed."
	echo "Your may need to alter your PostgreSQL configuration."
	echo "You can do this by running the supplied script:"
	echo "/usr/local/share/doc/openacs/adjust_pgqsl_conf.sh"; echo ""
	echo "Alternatively you can follow the instructions at:"
	echo "http://openacs.org/xowiki/How_to_install_in_Postgres_8.x"
	echo "****************************************************************"
fi
