#! /bin/sh
#
# Description: PostgreSQL streaming repliation node failover script
#               - promote execute
#
# Author:      Solbox Storage dev team 
#              - storage.sd@solbox.com

## EDIT FROM HERE
# Installation prefix
prefix=/user/db/pgsql

# Data directory
PGDATA="$prefix/data"

# Who to run the postmaster as, usually "postgres".  (NOT "root")
PGUSER=pgsql

## STOP EDITING HERE


# PID file
PIDFILE="$PGDATA/postmaster.pid"

# What to use to control command  the postmaster
PGCTL="$prefix/bin/pg_ctl"

# Stnadby DB recovery.conf file
STANDBYDBCONF="$PGDATA/recovery.conf"

# The path that is to be used for the script
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin


# Parse command line parameters.
case $1 in
	start)
	# DB active and promote => normal
	# etc => error
	if [ -f $PIDFILE ] ; then
		echo -n "Starting PostgreSQL Promote: "
		su - $PGUSER -c "$PGCTL promote"
	else
		echo "Error: PostgreSQL is already stopped."
		exit 1
	fi
	;;

	stop)
	echo -n "Stopping PostgreSQL: "
	su - $PGUSER -c "$PGCTL stop --mode=fast"
	echo "OK"
	;;

	status)
	# Normal staus => print OK
	# - DB active (pid exist ) 
	# - AND Primary mode (recovery.conf not exist)
	# Error status
	# - etc ( DB not started or Standby mode )
	if [ -f $PIDFILE ] ; then
		if [ ! -f $STANDBYDBCONF ] ; then
			echo "PostgreSQL running as a primary [OK]"
		else
			echo "PostgreSQL is standby status."
		fi
	else
		echo "PostgreSQL is already stopped."
	fi
	;;

	*)
	# Print help
	echo "Usage: $0 {start|stop|status}" 1>&2
	exit 1
	;;

esac

exit 0

