#! /bin/bash
#
# NOTE TO SYSTEM ADMINISTRATORS #
# To stop postgresql running, use the update-rc.d facility, or file-rc
# from the file-rc package.

export PATH=$PATH:/sbin:/usr/sbin:/bin:/usr/bin

startup () {
        touch ${POSTGRES_LOG:=/var/log/postgresql/postgres.log}
        chown postgres.postgres $POSTGRES_LOG
	# Clear away postmaster.pid if it doesn't match a running process
	if [ -f $PGDATA/postmaster.pid ]
	then
		running_process=$(ps -p $(cat $PGDATA/postmaster.pid | head -1) | grep -v PID | awk '{print $NF}')
		if [ "$running_process" != postmaster ]
		then
			rm $PGDATA/postmaster.pid
		fi
	fi
        /sbin/start-stop-daemon --pidfile $PGDATA/postmaster.pid --chuid postgres --startas /usr/lib/postgresql/bin/postgresql-startup --start
	# set file-max kernel parameter
	. /etc/postgresql/postmaster.conf
	fmaxfile=/proc/sys/kernel/file-max
	if [ ! -r $fmaxfile ]
	then
		fmaxfile=/proc/sys/kernel/fs/file-max
		if [ ! -r $fmaxfile ]
		then
			fmaxfile=/proc/sys/fs/file-max
			if [ ! -r $fmaxfile ]
			then
				fmaxfile=
			fi
		fi
	fi

	if [ -n "$fmaxfile" ]
	then
		fmax=`cat $fmaxfile`
		if [ $fmax -lt ${KERNEL_FILE_MAX:=1032} ]
		then
			echo ${KERNEL_FILE_MAX} > $fmaxfile
		fi
	fi
}

if [ ! $EUID -eq 0 ]
then
	echo $0 needs to be run by root.
	exit 1
fi

POSTMASTER=/usr/lib/postgresql/bin/postmaster
[ -x $POSTMASTER ] || exit

PG_CTL=/usr/lib/postgresql/bin/pg_ctl
if [ -r /etc/postgresql/postmaster.conf ]
then
	. /etc/postgresql/postmaster.conf
else
	echo /etc/postgresql/postmaster.conf is missing; cannot start postgresql
	exit 1
fi
PGDATA=${POSTGRES_DATA:-/var/lib/postgres/data}
export PGDATA

## Use of pg_ctl to stop the postmaster:
## we use pg_ctl stop -m fast, which will abort and roll back any current
## transactions.  Don't use -immediate, because it's equivalent to 
## kill -9.  Don't use -smart because it waits for people to disconnect
## and we want to force them off when we are shutting down or else the 
## system itself will do a kill -9 to get rid of us.

case "$1" in
    start)
        startup
        ;;
    stop)
        echo "Stopping PostgreSQL database: postmaster"
        $PG_CTL stop -w -m fast
	echo "."
        ;;
    restart)
        echo "Restarting PostgreSQL database: postmaster"
        $PG_CTL stop -w -m fast
        startup
	echo "."
        ;;
    force-reload | reload)
        $PG_CTL reload -D ${PGDATA}
        ;;
    status)
    	$PG_CTL status
    	;;
    *)
        echo "Usage: /etc/init.d/postgresql {start|stop|restart|reload|force-reload|status}"
        exit 1
        ;;
esac

exit 0

