#!/bin/sh
#
# HISTORY
#   Creation:	04/02/96
#   Auther:	Jun Kuwamura <juk@yokohama.email.ne.jp>
#
# 2006-12-22 JuK Mod use pg_ctl for 8.2
# 2003-01-08 JuK Add reload
# 2002-02-08 JuK Mod PGROOT to the short name of postgresql
# 2001-09-15 JuK Add Remove postmaster.pid when startup
# 2001-04-12 JuK Rmv -B and -o '-F' options for 7.1(using postgresql.conf)
# 2000-08-04 JuK Add postgres path in PGPORT
# 1999-10-06 JuK Mod PGOPT
# 1999-08-28 JuK Add status,restart
# 1999-02-27 JuK Add -b option.
# 1998-03-04 JuK Add -i option for 6.3.
# 1997-03-17 JuK Mod for user's shell.
# 1997-03-13 JuK Modified for PostgreSQL
#
PGOWNER=postgres
#PGOWNER=juk
PGROOT=/opt/pgsql
export PGDATA=$PGROOT/data
export PGPORT=5432
export PGOPT="-D $PGDATA"
PG_CTL=$PGROOT/bin/pg_ctl
daemoname="PostgreSQL server(postgres)"
ME=`whoami`

# Linux
pid=`ps ax | grep  $PGROOT/bin/postgres  | grep -v grep |  sed -e 's/^  *//' -e 's/ .*//' `

#
# start or stop postmaster (postgres daemon)
#
case $1 in
'start')
	if [ -x $PG_CTL ]; then
		if [ "X$pid" = "X" ]; then
		#	$PG_CTL
			if [ -S /tmp/.s.PGSQL.$PGPORT ]; then
				echo "removing /tmp/.s.PGSQL.$PGPORT"
				rm -f /tmp/.s.PGSQL.$PGPORT
			fi
			if [ -f $PGDATA/postmaster.pid ]; then
				echo "removing $PGDATA/postmaster.pid"
				rm -f $PGDATA/postmaster.pid
			fi
			if [ "$PGOWNER" = "$ME" ]; then
				$PG_CTL start $PGOPT
			else
				/bin/su - $PGOWNER -c "$PG_CTL start $PGOPT"
			fi
			pid=`ps ax | grep postmaster  | grep -v grep |  sed -e 's/^  *//' -e 's/ .*//' `
			if [ "X$pid" = "X" ]; then
				echo "$0: start failed."
			else
				echo "$0: $daemoname started."
				echo "$0: Proccess ID = $pid"
			fi
		else
			echo "$0: $daemoname is ALREADY running(PID = $pid)."
		fi
	else
		echo "$0: $PG_CTL does NOT exist."
		exit 1
	fi
        ;;
'stop')
	if [ -f $PG_CTL ]; then
		if [ "$PGOWNER" = "$ME" ]; then
			$PG_CTL stop $PGOPT
		else
			/bin/su $PGOWNER -c "$PG_CTL stop $PGOPT" || (echo su failed.; exit)
		fi
		echo "$0: $daemoname has been killed."
	fi
        ;;
'reload')
	if [ -f $PG_CTL ]; then
		if [ "$PGOWNER" = "$ME" ]; then
			$PG_CTL reload $PGOPT
		else
			/bin/su $PGOWNER -c "$PG_CTL reload $PGOPT" || (echo su failed.; exit)
		fi
		echo "$0: $daemoname has reloaded configuration."
	fi
        ;;
'status')
	if [ "$PGOWNER" = "$ME" ]; then
		$PG_CTL status $PGOPT
	else
		/bin/su - $PGOWNER -c "$PG_CTL status $PGOPT"
	fi
	;;
'restart')
	$0 stop
	$0 start
	;;
*)
        echo "usage: $0 {start|stop|status|restart}"

	$0 status

	if [ "X$pid" != "X" ]; then
		echo "$0: $daemoname is ALREADY running." #(PID = $pid)
	else
		echo "$0: $daemoname daemon is NOT running."
		if [ -S /tmp/.s.PGSQL.$PGPORT ]; then
			echo "    /tmp/.s.PGSQL.$PGPORT exists."
			echo "    postmaster must has been died abnormaly."
		fi
	fi
	exit 1
        ;;
esac
exit 0
