#! /bin/bash
## WARNING TO MAINTAINERS - DO NOT EDIT this file in debian/.  It will be
## overwritten by debian/rules.  Edit the .in template instead.
set -e
#
# Initialisation
#
# (This should set up values for POSTGRES_HOME and POSTGRES_DATA, which
# say where the library and database are.  It should also set up DATEFORMAT
# which governs whether the backend sends back dates in European or
# American format, and the logging options.)
# 
# Although Debian policy requires that this file be treated as an
# administrator-alterable conffile, you should NOT treat it as such.
# If you wish to change any values, the proper place to do so is in
# /etc/postgresql/postmaster.conf or /etc/postgresql/postgresql.conf.
#
# To stop postgresql running, use the update-rc.d facility, or file-rc
# if you have that package installed.

check_version () {
	# compare the database format with the format expected by the software
	dbformat=`cat ${PGDATA}/PG_VERSION 2>/dev/null`
	if [ A${dbformat} != A${version} ]
	then
	    if [ -z "${dbformat}" ]
	    then
		echo The database framework has not yet been created. Use
		echo initdb to do this.
	    else
		   echo The database is in an older format that cannot be read by
		   echo version ${version} of PostgreSQL.
		   echo
		if [ -f /var/lib/postgres/dumpall/default_encoding ]
		then
		   echo "The postinstallation script should attempt to upgrade the database"
		   echo "automatically.  If it fails, it must be done by hand."
		else
		   echo Run postgresql-dump to dump the old database and to reload
		   echo it in the new format.
	       fi
	       echo "*** READ /usr/share/doc/postgresql/README.Debian.migration.gz FIRST! ***"
	    fi
	    echo
	    echo The version ${version} postmaster cannot be started until
	    echo this is done.
	    exit 255
	fi
}

obsolete_config () {
	echo "
	******************  Obsolete configuration files  *****************
	
	postmaster.init and pg_options in /etc/postgresql/ are obsolete.

	Please update your configuration files by integrating your site-
	specific changes with the new format in postmaster.conf and
   postgresql.conf and delete or rename the old configuration files.

   PostgreSQL cannot be started until you have done this.

	*******************************************************************
	"
   exit 1
}

# Refuse to proceed if the old config files are still there
if [ -f /etc/postgresql/postmaster.init -o -f /etc/postgresql/pg_options ]
then
	 obsolete_config
	 exit 1
fi

. /etc/postgresql/postmaster.conf

export LANG PGDATESTYLE

if [ -z "${PGDATESTYLE}" ]
then
	PGDATESTYLE=ISO,European
fi

PGDATA=${POSTGRES_DATA:-/var/lib/postgres/data}
PGLIB=/usr/lib/postgresql
export PGLIB PGDATA
POSTMASTER=${PGLIB}/bin/postmaster
version=7.3		# Note: this is not necessarily the same as the
			# software version.

if grep -qs '^local.*[ 	]*peer[ 	]' /etc/postgresql/pg_hba.conf
then
	echo "Invalid pg_hba.conf authentication spec.  Change all occurrences of
peer authentication to ident in /etc/postgresql/pg_hba.conf."
	exit 1
fi

# Make sure we have a database directory
if [ ! -d ${PGDATA} ]
then
    echo No readable database directory for postgresql
    exit 3
fi

if [ ! -d ${PGDATA}/base ]
then
    echo There is no PostgreSQL database framework in $PGDATA.
    echo Run initdb as the postgres user to create it
    exit 3
fi

# First, check that the database is the right version
check_version

# Make sure that we don't try to start if the executable is missing.
if [ ! -x ${POSTMASTER} ]
then
    echo No postmaster executable for postgresql
    exit 3
fi

OPTIONS=$POSTMASTER_OPTIONS
if [ -n "$PGPORT" ]
then
	OPTIONS="$OPTIONS -p$PGPORT"
fi

if [ -n "$OPTIONS" ]
then
	OPTIONS="-o '$OPTIONS'"
fi

# Make sure there is no UNIX-socket file lurking around; this socket
# can get left behind if there is a system crash.
if [ -S /var/run/postgresql/.s.PGSQL.${PGPORT:=5432} ]
then
    # First of all, make sure the postmaster is not running

    # PostgreSQL uses its data dir as a place for a pid file that is
    # also used as a lock. Since this is not under /var/lock, and not
    # cleaned up automatically in Debian at startup, we need to see
    # if there is a stale pid file left when the system crashed:
    if [ -f "$PGDATA/postmaster.pid" ]; then
        # Is there a proc with this pid?
        PREVIOUS_PID=`sed -n '1 p' $PGDATA/postmaster.pid`
        if [ ! -d "/proc/$PREVIOUS_PID" ]; then
            echo "Removing stale PID file: $PGDATA/postmaster.pid"
            rm "$PGDATA/postmaster.pid";
        else
            # Check if the pid of the proc is really of a postmaster:
            if [ -z "`grep postmaster /proc/$PREVIOUS_PID/cmdline`" ]; then
                echo "Removing stale PID file: $PGDATA/postmaster.pid"
                rm "$PGDATA/postmaster.pid";
            fi
        fi
    fi

    if [ !  -f "$PGDATA/postmaster.pid" ]; then
	# It really is stale, so remove it
	rm /var/run/postgresql/.s.PGSQL.${PGPORT}
    else
	echo The postmaster is already running
        exit 0
    fi
fi

LOG_OPT="-l ${POSTGRES_LOG:=/var/log/postgresql/postgres.log}"

# Ready to go: stand clear...
echo Starting PostgreSQL postmaster.
cd ${POSTGRES_HOME}
eval /usr/lib/postgresql/bin/pg_ctl start -D ${PGDATA} ${LOG_OPT} ${OPTIONS}

#  Give it a chance to get going
sleep 5

exit 0

