#!/bin/sh
#
# glusterfsd	GlusterFS Daemon
#
# chkconfig:	345 14 89
#
# description:	GlusterFS Daemon
#

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

# Get network config
. /etc/sysconfig/network


# Get service config - may override defaults
# [ -f /etc/sysconfig/glusterfsd ] && . /etc/sysconfig/glusterfsd

# Check that networking is up.
if is_yes "${NETWORKING}"; then
	if [ ! -f /var/lock/subsys/network -a "$1" != stop -a "$1" != status ]; then
		msg_network_down glusterfsd
		exit 1
	fi
else
	exit 0
fi

test -x /usr/sbin/glusterfsd || exit 0

start() {
	# Check if the service is already running?
	if [ ! -f /var/lock/subsys/glusterfsd ]; then
		msg_starting glusterfsd
		daemon /usr/sbin/glusterfsd -p /var/run/glusterfsd.pid  
		RETVAL=$?
		[ $RETVAL -eq 0 ] && touch /var/lock/subsys/glusterfsd
	else
		msg_already_running glusterfsd
	fi
}


stop() {
	if [ -f /var/lock/subsys/glusterfsd ]; then
		# Stop daemons.
		msg_stopping glusterfsd
		killproc --pidfile /var/run/glusterfsd.pid glusterfsd -TERM
		rm -f /var/lock/subsys/glusterfsd
        # Killing remaining GlusterFS volume handling processes"
        for PID in $(find /var/lib/glusterd/ -type f -name "*.pid" -exec cat {} \;); do
            msg_stopping  "glusterfs volume daemon (${PID})"
	    ## TODO: Find pidfiles instead of pids and use:     killproc --pidfile ${PIDFILE} -TERM
	    kill -TERM ${PID}
        done
		
	else
		msg_not_running glusterfsd
	fi
}

condrestart() {
	if [ -f /var/lock/subsys/glusterfsd ]; then
		stop
		start
	else
		msg_not_running glusterfsd
		RETVAL=$1
	fi
}

RETVAL=0
# See how we were called.
case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  restart)
	stop
	start
	;;
  try-restart)
	condrestart 0
	;;
  force-reload)
	condrestart 7
	;;
  status)
	status glusterfsd
	RETVAL=$?
	# Listing volume daemons
	ls -la /var/lib/glusterd/vols/*/run/*.pid
	;;
  *)
	msg_usage "$0 {start|stop|restart|try-restart|force-reload|status}"
	exit 3
esac

exit $RETVAL
