#!/bin/bash

### BEGIN INIT INFO
# Provides:		openerp-server
# Required-Start:	$remote_fs $syslog
# Required-Stop:	$remote_fs $syslog
# Should-Start: 	$network
# Should-Stop:		$network
# Default-Start:	2 3 4 5
# Default-Stop: 	0 1 6
# Short-Description:	Enterprise Resource Management software
# Description:		Open ERP is a complete ERP and CRM software.
### END INIT INFO

PATH=/bin:/sbin:/usr/bin:/usr/local/bin
DAEMON=/usr/local/pgsql/bin/postgres
NAME=postmaster
DESC=postgresql

# Specify the user name (Default: openerp).
USER=postgres

# Specify an alternate data dir (Default: /usr/local/pgsql/data).
DATADIR="/var/postgres/data"


# pidfile
PIDFILE="$DATADIR/$NAME.pid"

# pid process
PIDPROCESS=`ps -ax | grep '[p]ostgres' | grep 'local' | awk '{ print $1 }'`

#pid file process running?
KILLED=1
if [ -f "$PIDFILE" ]; then
	pid=$(head -n 1 $PIDFILE)
	kill -0 $pid
	KILLED=$?      
fi

# Additional options that are passed to the Daemon.
DAEMON_OPTS=" -D $DATADIR"

[ -x $DAEMON ] || exit 0
[ -d $DATADIR ] || exit 0

killopenerp() {
      if [ "$PIDPROCESS" != "" ]; then
		 kill -TERM $PIDPROCESS
      fi
      if [ -f "$PIDFILE" ]; then
		 rm $PIDFILE
      fi
}
startopenerp() {
      $DAEMON $DAEMON_OPTS 
}
START=startopenerp
STOP=killopenerp

case "$1" in
    start)
	if [ "$KILLED" != 0 ]; then
		echo -n "Starting PostgreSQL daemon:"
		echo -n " postgres"
		$START
		echo "."
	else
		echo "PostgreSQL server is running: postgres."
	fi
	;;
    stop)
	if [ "$KILLED" != 0 ]; then
		echo "PostgreSQL server is not running:  OpenERP daemon: postgres."   
	fi
	echo -n "Stopping PostgreSQL daemon:"
	echo -n " postgres"
	$STOP
	echo "."
	;;
    reload|restart|force-reload)
		echo -n "Restarting PostgreSQL daemon:"
		$STOP
		sleep 10
		$START
		echo -n " postgres"
	;;
    *)
	echo "Usage: /usr/local/libexec/pgsql-server {start|stop|reload|restart}"
	exit 1
	;;
esac

exit 0
