#!/bin/bash
#
# chkconfig: 35 20 80
# description: Gluster File System service for volume management
#

# Get function from functions library
. /etc/rc.d/init.d/functions

BASE=glusterd
PIDFILE=/var/run/$BASE.pid
PID=`test -f $PIDFILE && cat $PIDFILE`
GLUSTERFSD=glusterfsd
GLUSTERFS=glusterfs
GLUSTERD_BIN=/usr/local/sbin/$BASE
GLUSTERD_OPTS="--pid-file=$PIDFILE"
GLUSTERD="$GLUSTERD_BIN $GLUSTERD_OPTS"
RETVAL=0

# Start the service $BASE
start()
{
       pidofproc -p $PIDFILE $GLUSTERD_BIN &> /dev/null
       status=$?
       if [ $status -eq 0 ]; then
           echo "glusterd service is already running with pid $PID"
           exit 1
       else
           echo -n $"Starting $BASE:"
           daemon $GLUSTERD
           RETVAL=$?
           echo
           [ $RETVAL -ne 0 ] && exit $RETVAL
       fi

}

# Stop the service $BASE
stop()
{
    echo -n $"Stopping $BASE:"
    pidofproc -p $PIDFILE $GLUSTERD_BIN &> /dev/null
    status=$?
    if [ $status -eq 0 ]; then
        killproc -p $PIDFILE $BASE
        [ -w $PIDFILE ] && rm -f $PIDFILE
    else
        killproc $BASE
    fi

    echo
    pidof -c -o %PPID -x $GLUSTERFSD &> /dev/null
    [ $? -eq 0 ] &&  killproc $GLUSTERFSD &> /dev/null

       #pidof -c -o %PPID -x $GLUSTERFS &> /dev/null
       #[ $? -eq 0 ] &&  killproc $GLUSTERFS &> /dev/null

    if [ -f /etc/glusterd/nfs/run/nfs.pid ] ;then
        pid=`cat /etc/glusterd/nfs/run/nfs.pid`;
        cmd=`ps -p $pid -o comm=`

        if [ $cmd == "glusterfs" ]; then
            kill `cat /etc/glusterd/nfs/run/nfs.pid`
        fi
    fi
}


### service arguments ###
case $1 in
    start)
        start
        ;;
    stop)
        stop
        ;;
    status)
        status $BASE
        ;;
    restart)
        $0 stop
        $0 start
        ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart}."
        exit 1
esac

exit 0
