#!/bin/sh
#
# chkconfig: 35 99 99
# description: {{description}}
#
# Author: {{author}}
# Created: {{created}}

. /etc/rc.d/init.d/functions

PIDFILE="{{pidroot}}/{{label}}.pid"
#ps -fe | grep "{{label}}" | head -n1 | cut -d" " -f 6 > ${PIDFILE}

USER={{user}}
DAEMON={{execpath}}
SCRIPT={{script}}
LABEL={{label}}
LOG_FILE={{logroot}}/{{label}}.log
LOCK_FILE=/var/lock/subsys/node-daemon-$LABEL

do_start()
{
  if [ ! -f "${LOCK_FILE}" ] ; then
    su - ${USER} -s /bin/sh -c "$DAEMON $SCRIPT {{{wrappercode}}} >> $LOG_FILE 2>&1 </dev/null & echo \$!"  > ${PIDFILE}
    RETVAL=$?
    [ $RETVAL -eq 0 ] && touch ${LOCK_FILE}
  else
    echo "$LABEL is locked with ${LOCK_FILE}."
    RETVAL=1
  fi
  [ $RETVAL -eq 0 ] && echo_success || echo_failure
}

do_stop()
{
  echo -n "Stopping $LABEL:"
  PID=`cat ${PIDFILE}`
  kill $PID > /dev/null
  TIMEOUT={{stoptimeout}}
  # wait for process to exit
  # if waiting longer than the timeout send a SIGKILL
  while kill -0 $PID 2>/dev/null; do 
    if [ $TIMEOUT -le 0 ]; then
      kill -9 $PID
      echo "Process didn't exit before timeout, sent SIGKILL"
    fi
    sleep 1;
    ((TIMEOUT--));
  done;
  if [ -f ${LOCK_FILE} ] ; then
    rm ${LOCK_FILE}
  fi
  if [ -f ${PIDFILE} ] ; then
    rm ${PIDFILE}
  fi
  RETVAL=$?
  echo
  [ $RETVAL -eq 0 ] && echo_success || echo_failure
}

case "$1" in
  start)
    do_start
    ;;
  stop)
    do_stop
    ;;
  restart)
    do_stop
    do_start
    ;;
  status)
    running="no"
    if [ -f ${PIDFILE} ]; then
      PID=$(cat ${PIDFILE})
      if [ -x /proc/${PID} ]; then
        running="yes"
      fi
    fi

    if [ "${running}" == "yes" ]; then
      echo "${LABEL} is running ($PID)"
    else
      echo "${LABEL} is not running"
    fi
    ;;
  *)
    echo "Usage: $0 {start|stop|restart|status}"
    RETVAL=1
esac

exit $RETVAL
