#! /bin/bash
#
# gfarm-pgsql	Start the PostgreSQL daemon - postmaster.
#

PATH=/sbin:/bin:/usr/sbin:/usr/bin

FILE="gfarm-pgsql"

PGPORT="@config_gfarm_backend_port@"
PGDATA="@config_gfarm_backend_data_dir@"
CTL="@config_gfarm_pgsql_bindir@/pg_ctl"
PIDFILE="$PGDATA/portmaster.pid"
OPTIONS="@config_gfarm_pgsql_options@"
PRIVILEGE="@config_gfarm_backend_privilege@"
# For SELinux we need to use 'runuser' not 'su'
[ -x /sbin/runuser ] && SU=/sbin/runuser || SU=su
case $PRIVILEGE in
'')	RUN=/bin/sh;;
*)	RUN="$SU - $PRIVILEGE";;
esac

trap "" 1
export LANG=C
export PATH
export PGPORT
export PGDATA

test -f $CTL || exit 0
test -d $PGDATA || exit 0

call_pg_ctl()
{
	$RUN -c "$CTL $OPTIONS $*"
}

checkstatus()
{
	call_pg_ctl status
	RETVAL=$?
	[ $RETVAL -eq 1 ] && RETVAL=3
	return $RETVAL
}

wait_to_start()
{
	iter=0
	while if checkstatus; then false; else true; fi >/dev/null 2>&1
	do
		iter=`expr $iter + 1`
		[ $iter -gt 6 ] && exit 1
		sleep 5
	done
	# XXX - checkstatus cannot ensure the database really starts up
	sleep 3
}

RETVAL=0

case "$1" in
  start)
	# from /usr/share/postgresql-common/init.d-functions on Ubuntu 12.04:
	# postgres package on Ubuntu 12.04 needs /var/run/postgresql
	# for its UNIX socket file.
	# XXX this won't work, if $PRIVILEGE != postgres, and
	# both gfarm-pgsql and the system supplied postgres are used.
	d=/var/run/postgresql
	if [ -d $d -a -w $d  ]; then
		chown $PRIVILEGE $d
		chgrp $PRIVILEGE $d # it's ok that even this fails
		chmod 2775 $d
	elif [ -w `dirname $d` ]; then
		install -d -m 2775 -o $PRIVILEGE -g $PRIVILEGE $d
	fi

	echo -n "Starting gfarm server: $FILE"
	checkstatus > /dev/null
	RETVAL=$?
	if [ $RETVAL -ne 0 ]; then
		call_pg_ctl start
		RETVAL=$?
	fi
	wait_to_start
	echo "."
	;;
  stop)
	echo -n "Stopping gfarm server: $FILE"
	checkstatus > /dev/null
	RETVAL=$?
	if [ $RETVAL -eq 3 ]; then
		RETVAL=0
	else
		call_pg_ctl stop > /dev/null
		RETVAL=$?
	fi
	echo "."
	;;
  status)
	checkstatus
	RETVAL=$?
	;;
  restart)
	call_pg_ctl restart > /dev/null
	RETVAL=$?
	;;
  force-reload)
	call_pg_ctl reload
	RETVAL=$?
	;;
  *)
	echo "Usage: /etc/init.d/$FILE {start|stop|restart}"
	exit 1
	;;
esac

exit $RETVAL
