#! /bin/sh
# This script is run only during upgrade of a postgresql Debian package.
# It is not intended for normal use.

if [ -f /etc/postgresql/postgresql.env ]
then
	. /etc/postgresql/postgresql.env
else
	echo $0: cannot find /etc/postgresql/postgresql.env
	exit 1
fi

PGPORT=5341
export PGPORT

if [ ! -f $PGDATA/PG_VERSION ]
then
	echo $0: Cannot find database; unable to dump a database structure for
	echo potential upgrades.
	exit 2
else
	PG_VERSION=`cat $PGDATA/PG_VERSION`
fi

PATH=/bin:/usr/bin:/usr/lib/postgresql/bin:/usr/lib/postgresql/dumpall/$PG_VERSION
LD_LIBRARY_PATH=/usr/lib:/usr/lib/postgresql/dumpall/$PG_VERSION
export PATH LD_LIBRARY_PATH

cd /usr/lib/postgresql/dumpall
rm -f db.out.$$                     # just in case...
if pg_dumpall -s > db.out.$$
then
	cat $PGDATA/PG_VERSION > db.out.version
	rm -f db.out
	# "upgrade" MUST be the 3rd word in the first line of db.out
	echo "-- prerm upgrade on `date` from version `cat $PGDATA/PG_VERSION`" >db.out
	cat db.out.$$ >>db.out
	echo "-- prerm upgrade completed on `date`" >>db.out
	rm -f db.out.$$
	chmod 440 db.out

	# record the default encoding for initdb
	DEFAULT_ENCODING=`psql -qt -c "select encoding from pg_database where datname = 'template1'"`
	/usr/lib/postgresql/bin/pg_encoding $DEFAULT_ENCODING >default_encoding
else
	rm -f db.out.$$
	echo $0: pg_dumpall of database structure has failed
	exit 3
fi

exit 0
