#!/bin/bash
#
# EMIR-SERP
#
# chkconfig: 235 96 04
# description: EMIR-SERP
#
# Source function library.
. /etc/rc.d/init.d/functions

NAME="EMIR-SERP"

#This must be equal to this file name
SERVICE=emir-serp
DAEMON=/usr/bin/emir-serp
EMIR_SERP_USER=emi
LASTPID=/var/run/emi/emir-serp/emir-serp.pid

function start {
  if [ -f $LASTPID ]; then
    status -p "$LASTPID" "$SERVICE"
    RETVAL=$?
  else
    runuser -s /bin/bash -c "$DAEMON -p $LASTPID" "$EMIR_SERP_USER"
    RETVAL=$?
    echo -n "$NAME startup"
    [ "$RETVAL" -eq 0 ] && success || failure 
    echo
    [ $RETVAL -eq 0 ] && touch "/var/lock/subsys/$SERVICE"
  fi
}

function stop {
  kill -s SIGTERM `cat $LASTPID` >/dev/null 2>&1
  RETVAL=$?
  echo -n "$NAME shutdown"
  if [ "$RETVAL" -eq 0 ]; then
    until [ ! -f $LASTPID ]; do
      sleep 2
    done
    success 
  else
    failure
  fi
  echo
  [ $RETVAL -eq 0 ] && rm -f "/var/lock/subsys/$SERVICE"
}


# See how we were called.
RETVAL=0
case "$1" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  status)
        status -p "$LASTPID" "$SERVICE"
        RETVAL=$?
        ;;
  restart)
        stop
        start
        ;;
  *)
        echo $"Usage: $0 {start|stop|status|restart|help}"
        exit 1
esac

exit $RETVAL
