#!/bin/bash
#
# rcouch Distributed Data Store
#
# chkconfig: 2345 80 30
# description: rcouch is a distrubuted data store.
# processname: beam
# config: /etc/rcouch/app.config
# config: /etc/rcouch/vm.args
#

# Source function library.
. /etc/rc.d/init.d/functions

#check for script,config, and data dirs
[ -x /usr/bin/rcouch ] || exit 0
[ -d /etc/rcouch ] || exit 0
[ -d /var/lib/rcouch ] || exit 0
[ -d /var/run/rcouch ] || exit 0

RETVAL=0

PATH=/sbin:/usr/sbin:/bin:/usr/bin
DESC="a decentralized data platform"
NAME=rcouch
DAEMON=/usr/bin/$NAME


start() {
        #Check if rcouch is running
        RETVAL=`$DAEMON ping`
        [ "$RETVAL" = "pong" ] && echo "rcouch is already running" && return 1

	# Start daemons.
	echo -n $"Starting rcouch: "
	su - rcouch -c "$DAEMON start" && success || failure $"$NAME start"
	RETVAL=$?
	[ $RETVAL -eq 0 ]
        echo
	return $RETVAL
}

stop() {
        # Stop daemon.
	echo -n $"Stopping rcouch: "
  	RETVAL=`su - rcouch -c "$DAEMON ping"`
  	[ "$RETVAL" = "pong" ] && su - rcouch -c "$DAEMON stop 2>/dev/null 1>&2"
        sleep 2
        RETVAL=`pidof beam.smp`
        [ "$RETVAL" = "" ] && success && echo && return 0 || failure $"$NAME stop"
        sleep 10
        RETVAL=`pidof beam.smp`
        [ "$RETVAL" = "" ] && success && echo && return 0 || failure $"$NAME failed to stop"
        echo
        return 1

}

reload() {
        # Restart the VM without exiting the process
	echo -n $"Reloading rcouch: "
  	RETVAL=`su - rcouch -c "$DAEMON ping"`
  	[ "$RETVAL" = "pong" ] && su - rcouch -c "$DAEMON restart 2>/dev/null 1>&2" \
        && success && echo && return 0 || failure $"$NAME restart"
        echo
	return $RETVAL
}


# See how we were called.
case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  restart)
 	stop
	start
	;;
  reload)
	reload
	;;
  ping)
	su - rcouch -c "$DAEMON ping" || exit $?
        ;;
  *)
	echo $"Usage: $0 {start|stop|reload|restart|ping}"
	exit 1
esac

exit $?
