#!/bin/bash
# postgresql	This is the init script for starting up the PostgreSQL
#		server
#
# chkconfig: - 64 36
# description: Starts and stops the PostgreSQL backend daemon that handles \
#	       all database requests.
# processname: postmaster
# pidfile: /var/run/postmaster.pid

# Version 6.5.3-2 Lamar Owen
# Added code to determine if PGDATA exists, whether it is current version
#     or not, and initdb if no PGDATA (initdb will not overwrite a database).

# Version 7.0 Lamar Owen
# Added logging code
# Changed PGDATA.

# Version 7.0.2 Trond Eivind Glomsrd <teg@redhat.com>
# use functions, add conditional restart
          
# Version 7.0.3 Lamar Owen <lamar@postgresql.org>
# Check for the existence of functions before blindly using them 
# in particular -- check for success () and failure () before using.
# More Cross-distribution support -- PGVERSION variable, and docdir checks.

# Version 7.1 Release Candidate Lamar Owen <lamar@postgresql.org>
# initdb parameters have changed.

# Version 7.1.2 Trond Eivind Glomsrd <teg@redhat.com>
# Specify shell for su
# Handle stop better - kill unwanted output, make it wait until the database is ready
# Handle locales slightly differently - always using "C" isn't a valid option 
# Kill output from database initialization 
# Mark messages for translation

# Version 7.1.2-2.PGDG Lamar Owen <lamar.owen@wgcr.org>
# sync up.
# Karl's fixes for some quoting issues.

# Version 7.2b2 Lamar Owen <lamar.owen@wgcr.org>
# version change.

# Version 7.2 final.  Lamar Owen <lamar.owen@wgcr.org>
# reload from Peter E.
# Eliminate the pidof postmaster test in stop -- we're using pg_ctl so we don't need pidof.
# Tested the $? return for the stop script -- it does in fact propagate.
# TODO: multiple postmasters.

# Version 7.3 Lamar Owen <lamar.owen@ramifordistat.net>
# Multiple postmasters, courtesy Karl DeBisschop

# Version 7.4 Lamar Owen.

# Version 7.4.3 Tom Lane <tgl@sss.pgh.pa.us>
# Support condstop for uninstall
# Minor other changes suggested by Fernando Nasser.

# Version 7.4.5 Tom Lane <tgl@sss.pgh.pa.us>
# Rewrite to start postmaster directly, rather than via pg_ctl; this avoids
# fooling the postmaster's stale-lockfile check by having too many
# postgres-owned processes laying about.

# Version 8.1 Devrim Gunduz <devrim@PostgreSQL.org>
# Increased sleep time from 1 sec to 2 sec.

# Version 8.2 Devrim Gunduz <devrim@CommandPrompt.com>
# Set initdb as a seperate option.

# PGVERSION is the full package version, e.g., 8.2.0
# Note: the specfile ordinarily updates this during install

PGVERSION=9.0.4

# PGMAJORVERSION is major version, e.g., 8.0 (this should match PG_VERSION)
PGMAJORVERSION=`echo "$PGVERSION" | sed 's/^\([0-9]*\.[0-9]*\).*$/\1/'`

# Set defaults for configuration variables
# (change it in /etc/sysconfig/postgresql)

PGENGINE=/usr/bin
PGPORT=5432
PGDATA=/var/lib/pgsql/data
LC_ALL=ru_RU.UTF-8

# For SELinux we need to use 'runuser' not 'su'
if [ -x /sbin/runuser ]
then
    SU=runuser
else
    SU=su
fi

PGLOG=/var/lib/pgsql/pgstartup.log

# Override defaults from /etc/sysconfig/postgresql if file is present
[ -f /etc/sysconfig/postgresql ] && . /etc/sysconfig/postgresql

export PGDATA
export PGPORT
export LC_ALL

[ -f "$PGENGINE/postmaster" ] || exit 1

script_result=0

SERVNAME=postgresql

OUTFORMAT=/etc/init.d/outformat
[ -x $OUTFORMAT ] || OUTFORMAT=/etc/init.d/$SERVNAME.outformat
if which tput >/dev/null && test -x $OUTFORMAT ; then
        . $OUTFORMAT
else
        MOVE_TO_COL(){ :; }
        SETCOLOR_SUCCESS(){ :; }
        SETCOLOR_FAILURE(){ :; }
        SETCOLOR_WARNING(){ :; }
        SETCOLOR_NORMAL(){ :; }
fi

success()
{
        MOVE_TO_COL
        echo -n '[ '
        SETCOLOR_SUCCESS
        echo -n 'DONE'
        SETCOLOR_NORMAL
        echo ' ]'
}

failure()
{
        MOVE_TO_COL
        echo -n '['
        SETCOLOR_FAILURE
        echo -n 'FAILED'
        SETCOLOR_NORMAL
        echo ']'
}

passed()
{
        MOVE_TO_COL
        echo -n '['
        SETCOLOR_WARNING
        echo -n 'PASSED'
        SETCOLOR_NORMAL
        echo ']'
}

# Find the name of the script
NAME=$SERVNAME

check_shmmax() {
    PGCONFNAME="postgresql.conf"
    if [ -e $PGDATA/$PGCONFNAME ] ; then
	PGCONF="$PGDATA/$PGCONFNAME"
    else
	PGCONF="/usr/share/pgsql/$PGCONFNAME.sample"
    fi
    PG_SHBUF=`cat $PGCONF | grep "shared_buffers = " | head -n1 | sed 's/^.*=\ //;s/MB.*$//'`
    SHMMAX=`sysctl -n kernel.shmmax`
    SHMMAX_MIN=`expr ${PG_SHBUF} \* 1024 \* 1024 \* 4`
    if [ ${SHMMAX} -lt ${SHMMAX_MIN} ] ; then
	echo "The current value of SHMMAX is too low for postgresql to run."
	echo "Please edit /etc/sysctl.conf and set this value to at least ${SHMMAX_MIN}:"
	echo "kernel.shmmax = ${SHMMAX_MIN}"
        exit 1
    fi

}

start(){
	# If not init - do it
	if [ ! -f "$PGDATA/PG_VERSION" ] && [ ! -d "$PGDATA/base" ]
	then
		initdb
	fi
	echo -n $"Starting ${NAME} service: "
	clean
        if [ -e /var/lock/subsys/${NAME} ] ; then
	    passed
	    exit 1
	fi
	# Make sure startup-time log file is valid
	if [ ! -e "$PGLOG" -a ! -h "$PGLOG" ]
	then
		touch "$PGLOG" || exit 1
		chown postgres:postgres "$PGLOG"
		chmod go-rwx "$PGLOG"
#		[ -x /usr/bin/chcon ] && /usr/bin/chcon -u system_u -r object_r -t postgresql_log_t "$PGLOG" 2>/dev/null
	fi

	# Check for the PGDATA structure
	if [ -f "$PGDATA/PG_VERSION" ] && [ -d "$PGDATA/base" ]
	then
	# Check version of existing PGDATA

		if [ x`cat "$PGDATA/PG_VERSION"` != x"$PGMAJORVERSION" ]
		then
			SYSDOCDIR="(Your System's documentation directory)"
			if [ -d "/usr/doc/postgresql-$PGVERSION" ]
			then
				SYSDOCDIR=/usr/doc
			fi
			if [ -d "/usr/share/doc/postgresql-$PGVERSION" ]
			then
				SYSDOCDIR=/usr/share/doc
			fi
			if [ -d "/usr/doc/packages/postgresql-$PGVERSION" ]
			then
				SYSDOCDIR=/usr/doc/packages
			fi
			if [ -d "/usr/share/doc/packages/postgresql-$PGVERSION" ]
			then
				SYSDOCDIR=/usr/share/doc/packages
			fi
			echo
			echo $"An old version of the database format was found."
			echo $"You need to upgrade the data format before using PostgreSQL."
			echo $"See $SYSDOCDIR/postgresql-$PGVERSION/README.rpm-dist for more information."
			exit 1
		fi

	# No existing PGDATA! Warn the user to initdb it.

	else
		echo
		echo "$PGDATA is missing. Use \"service postgresql initdb\" to initialize the cluster first."
		failure
		echo
		exit 1
 	fi


	$SU -s /bin/sh -l postgres -c "$PGENGINE/postmaster -p '$PGPORT' -D '$PGDATA' ${PGOPTS} &" >> "$PGLOG" 2>&1 < /dev/null
	sleep 2
	pid=`pidof -s "$PGENGINE/postmaster"`
	if [ $pid ] && [ -f "$PGDATA/postmaster.pid" ]
	then
		success "$PSQL_START"
#hack for *deb
		if [ -d /var/lock/subsys ] ; then 
			touch /var/lock/subsys/${NAME}
		else
			mkdir -p /var/lock/subsys
			touch /var/lock/subsys/${NAME}
		fi
		head -n 1 "$PGDATA/postmaster.pid" > "/var/run/postmaster.${PGPORT}.pid"
	else
		failure
		script_result=1
	fi
}

stop(){
	echo -n $"Stopping ${NAME} service: "
        if [ ! -e /var/lock/subsys/${NAME} ] ; then
	    passed
	else
	    $SU -l -s /bin/sh -c "$PGENGINE/pg_ctl stop -D $PGDATA" postgres > /dev/null 2>&1 < /dev/null
	    ret=$? 
	    if [ $ret -eq 0 ]
	    then
		success
		rm -f /var/run/postmaster.${PGPORT}.pid
		rm -f /var/lock/subsys/${NAME}
		rm -f $PGDATA/postmaster.pid
	    else
		failure
		script_result=1
	    fi
	fi
	echo

}

clean(){
	ISRUN=`$SU -l -s /bin/sh -c "$PGENGINE/pg_ctl status -D '$PGDATA' -s" postgres | grep "PID" | wc -l`
	if [ $ISRUN -eq 0 ]
	then
		rm -f /var/run/postmaster.${PGPORT}.pid
		rm -f /var/lock/subsys/${NAME}
		rm -f $PGDATA/postmaster.pid
	fi
}

restart(){
    stop
    start
}

initdb(){
		if [ -f "$PGDATA/PG_VERSION" ]
		then
			echo "Data directory is not empty!"
			failure
		else
			check_shmmax || exit 1
			echo -n $"Initializing database: "
			if [ ! -e "$PGDATA" -a ! -h "$PGDATA" ]
			then
				mkdir -p "$PGDATA" || exit 1
			fi
			chown postgres:postgres "$PGDATA"
			chmod go-rwx "$PGDATA"

			# Clean up SELinux tagging for PGDATA
#			[ -x /sbin/restorecon ] && /sbin/restorecon "$PGDATA"
			# Initialize the database
			$SU -l postgres -s /bin/sh -c "LC_ALL=$LC_ALL $PGENGINE/initdb --pgdata='$PGDATA' --auth='ident'" >> "$PGLOG" 2>&1 < /dev/null
			# Create directory for postmaster log
			mkdir "$PGDATA/pg_log"
			chown postgres:postgres "$PGDATA/pg_log"
			chmod go-rwx "$PGDATA/pg_log"

			[ -f "$PGDATA/PG_VERSION" ] && success
			[ ! -f "$PGDATA/PG_VERSION" ] && failure
			echo
		fi
}
condrestart(){
    [ -e /var/lock/subsys/${NAME} ] && restart
}

condstop(){
    [ -e /var/lock/subsys/${NAME} ] && stop
}

reload(){
    if [ -e /var/lock/subsys/${NAME} ] ; then
        $SU -l -s /bin/sh -c "$PGENGINE/pg_ctl reload -D '$PGDATA' -s" postgres > /dev/null 2>&1 < /dev/null
	success
    else
	passed
    fi
}

status() {
    $SU -l -s /bin/sh -c "$PGENGINE/pg_ctl status -D '$PGDATA' -s" postgres
#  > /dev/null 2>&1 < /dev/null
}

# This script is slightly unusual in that the name of the daemon (postmaster)
# is not the same as the name of the subsystem (postgresql)

# See how we were called.
case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  status)
	status
	;;
  restart)
	restart
	;;
  initdb)
	initdb
	;;
  condrestart)
	condrestart
	;;
  condstop)
	condstop
	;;
  reload|force-reload)
	reload
	;;
  *)
	echo $"Usage: $0 {start|stop|status|restart|condrestart|condstop|reload|force-reload|initdb}"
	exit 1
esac

exit $script_result
