#!/bin/sh
#
# chkconfig: 345 60 60
# description: stats collection daemon
# processname: spinstatsd
#

EXECPATH="/usr/sbin/spinstatsd"
[ -x ${EXECPATH} ] || exit 0

# define daemon options here
SDDOPTIONS=

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

BASEDIR=`dirname $0`

getParentPid() {
    pidlist=`/sbin/pidof -x $1`
    retval=$?
    if [ $retval -eq 0 ]; then
        ps -o pid,ppid $pidlist | awk '/[0-9]/{X[P=$1]=$2}END{while(X[P]in X)P=X[P];print P}'
        retval=$?
    fi
    return $retval;
}

spinstatsStart() {

    PID=`getParentPid "${EXECPATH}"`
    RETVAL=$?
    if [ $RETVAL -eq 0 -a -n "$PID" ]
	then
         echo "spinstatsd (pid ${PID}) is already running."
         return -1
    fi

    echo -n "starting spinstatsd:"
    (cd /core; $EXECPATH $SDDOPTIONS $*)
    echo

    if [ $UID -eq 0 ]; then
	PID=`getParentPid "${EXECPATH}"`
       echo  $PID > /var/run/spinstatsd.pid
    fi

    return 0
}

spinstatsStop() {
   PID=`getParentPid "${EXECPATH}"`
   RETVAL=$?
   if [ $RETVAL -eq 0 -a -n "$PID" ]
     then
       echo -n "stopping spinstatsd:"
       kill "$PID"
       RETVAL=$?
       [ $RETVAL -eq 0 ] && success "spinstatsd (pid ${PID}) stop" ||
       killproc ${EXECPATH} > /dev/null 2>&1
       echo
       RETVAL=$?          
   else
       echo "statsstatsd is not running."
   fi
   return $RETVAL
}

spinstatsStatus() {

    PID=`getParentPid "${EXECPATH}"`
    RETVAL=$?
    if [ $RETVAL -eq 0 -a -n "$PID" ]
      then
        echo "spinstatsd (pid ${PID}) is running..."
    else
        echo "spinstatsd is not running."
    fi
}

##########################################################
RETVAL=0

case "$1" in
  start)
        shift
        spinstatsStart "$*"
        RETVAL=$?
        ;;

  stop)
        shift
        spinstatsStop
        RETVAL=$?
        ;;

  restart)
        $0 stop
        sleep 2
        $0 start
        RETVAL=$?
        ;;

  status)
        spinstatsStatus
        RETVAL=$?
        ;;

  dump)
	/usr/sbin/dumpspinstats
        RETVAL=$?
        ;;
  *)
        echo "Usage: spinstats {start|stop|restart|status|dump}"
        exit 1
esac

exit $RETVAL
