#!/bin/sh
#
# $OpenBSD: INSTALL-server,v 1.1 2004/07/26 10:10:46 peter Exp $
#
# Pre/post-installation setup of postgresql

# use a sane path and install prefix
#
PATH=/bin:/usr/bin:/sbin:/usr/sbin
PREFIX=${PKG_PREFIX:-/usr/local}

PGHOME=/var/postgresql
PG=_postgresql
ID=503

# add user/group _postgresql if they don't already exist
do_accts()
{
	echo
	echo "+---------------------"

	groupinfo -e $PG
	if [ $? -eq 0 ]; then
		echo "| Using existing group '$PG'"
	else
		echo "| Creating group '$PG'"
		groupadd -g $ID $PG
	fi

	userinfo -e $PG
	if [ $? -eq 0 ]; then
		echo "| Using existing account '$PG'"
	else
		echo "| Creating user '$PG'"
		if [ -d $PGHOME ]; then
			PGCREATEHOME=""
		else
			PGCREATEHOME="-m"
		fi
		useradd -g $PG \
			-c "PostgreSQL Manager" \
			$PGCREATEHOME -d $PGHOME \
			-L daemon \
			-u $ID $PG
	fi

	echo "+---------------------"
	echo
}

do_initdb()
{
	if [ ! -d $PGHOME/data ]; then
		echo
		echo "+---------------------"
		echo "| Creating default database installation in:"
		echo "|"
		echo "|		 $PGHOME/data"
		echo "+---------------------"
		echo
		install -d -o $PG -g $PG -m 0775 $PGHOME/data
		su $PG -c "$PREFIX/bin/initdb -D $PGHOME/data"
		echo
	else
		echo
		echo "+---------------------"
		echo "| Leaving existing database installation in:"
		echo "|"
		echo "|		 $PGHOME/data"
		echo "|"
		echo "| Note that any previous database files are UNLIKELY to"
		echo "| be compatible with upgraded versions of $1"
		echo "| package."
		echo "|"
		echo "| DO NOT just try to start the database unless you"
		echo "| are absolutely sure that the existing files are"
		echo "| compatible with this version of $1."
		echo "|"
		echo "| See the $1 documentation and/or"
		echo "| $PREFIX/share/doc/postgresql/README.OpenBSD for"
		echo "| more information."
		echo "+---------------------"
		echo
	fi
}

# Function: tell the user what s/he needs to do to use the port just installed
#
do_notice()
{
	echo
	echo "+---------------------"
	echo "| The $1 package installation completed."
	echo "| See $PREFIX/share/doc/postgresql/README.OpenBSD for more"
	echo "| information on using PostgreSQL package in OpenBSD environment."
	echo "+---------------------"
	echo
}

# verify proper execution
#
if [ $# -ne 2 ]; then
	echo "usage: $0 distname { PRE-INSTALL | POST-INSTALL }" >&2
	exit 1
fi

# Verify/process the command
#
case $2 in
	PRE-INSTALL)
		do_accts $1
		;;
	POST-INSTALL)
		do_initdb $1
		do_notice $1
		;;
	*)
		echo "usage: $0 distname { PRE-INSTALL | POST-INSTALL }" >&2
		exit 1
		;;
esac

exit 0
