#!/bin/sh
#
# $NetBSD: INSTALL,v 1.4 2001/03/25 11:29:37 wennmach Exp $

PKGNAME=$1
STAGE=$2

USER=@PGUSER@
GROUP=@PGGROUP@
PGHOME=@PGHOME@

ADDUSER="@ADDUSER@"
ADDGROUP="@ADDGROUP@"
CAT="@CAT@"
CHGRP="@CHGRP@"
CHMOD="@CHMOD@"
CHOWN="@CHOWN@"
CP="@CP@"
GREP="@GREP@"
MKDIR="@MKDIR@"
RM="@RM@"
SU="@SU@"
TOUCH="@TOUCH@"

case ${STAGE} in
PRE-INSTALL)
	${CAT} << EOF
------------------------------------------------------------
Dump existing databases, before installing new db version !!
------------------------------------------------------------
EOF
	# Group... the default's shipped with NetBSD
	# We need to check that ${GROUP} exists before adding the user.
	# Do it with chgrp to be able to use NIS.
	#
	${TOUCH} "/tmp/grouptest.$$"
	${CHGRP} ${GROUP} "/tmp/grouptest.$$" >/dev/null 2>&1
	if [ $? -eq 0 ]
	then
		echo "Group '${GROUP}' already exists...proceeding."
	else
		echo "Creating '${GROUP}' group..."
		${ADDGROUP} ${GROUP}
		echo "Done."
	fi
	${RM} -f "/tmp/grouptest.$$"

	# Use `finger' to be able to use NIS.
	#
	finger ${USER} 2>&1 | ${GREP} -q "no such user"
	if [ $? -eq 0 ]
	then
		echo "Creating '${USER}' user..."
		${ADDUSER} \
			-c "PostgreSQL database administrator" \
			-d ${PGHOME} \
			-g ${GROUP} \
			-s /bin/sh \
			${USER}
	# "useradd -d" in NetBSD-1.5 creates a home directory and  populates
	# it with dot files regardless if -m was given or not. This behaviour
	# was changed in later versions. We delete the newly created .profile
	# here so that the sample profile.pgsql  gets installed in the
	# POST-INSTALL stage.
		${RM} -f ${PGHOME}/.profile
		echo "Done."
	else
		echo "User '${USER}' already exists...proceeding."
	fi
	${MKDIR} ${PGHOME}
	${CHOWN} -R ${USER}:${GROUP} ${PGHOME}
	;;

POST-INSTALL)
	if [ ! -f ${PGHOME}/.profile ]; then
		${CP} ${PKG_PREFIX}/share/postgresql/profile.pgsql.sample \
			${PGHOME}/.profile
		${CHOWN} ${USER} ${PGHOME}/.profile
		${CHMOD} 644 ${PGHOME}/.profile
	fi
	${CAT} << EOF
------------------------------------------------------------------
Initializing PostgreSQL Databases - this may take a few minutes...
------------------------------------------------------------------
EOF
        echo "${PKG_PREFIX}/bin/initdb --pglib=${PKG_PREFIX}/share/postgresql --pgdata=${PGHOME}/data" | ${SU} -l ${USER}
	;;

*)
	echo "Unexpected argument: ${STAGE}"
	exit 1
	;;
esac
exit 0
