#!/bin/bash
### BEGIN INIT INFO
# Provides:          owl-daemon
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Put a short description of the service here
# Description:       Put a long description of the service here
### END INIT INFO

# General variables
DAEMON=harp-agent
USER=root

##################################################

PATH=/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin
RETVAL=0
LOGDIRECTORY="/var/log/${DAEMON}"
LOGFILE="/var/log/${DAEMON}/${DAEMON}.log"
PIDFILE="/var/run/${DAEMON}.pid"

# detect the distribution:
if [ -f /etc/redhat-release -o -f /etc/fedora-release ] ; then
  DISTRIBUTION="redhat"
elif [ -f /etc/SuSE-release ] ; then
  DISTRIBUTION="suse"
elif [ -f /etc/debian_version ] ; then
  DISTRIBUTION="debian"
else
  DISTRIBUTION="debian"
fi

# Source function library.
[ "$DISTRIBUTION" = "redhat" ] && . /etc/init.d/functions
[ "$DISTRIBUTION" = "suse" ] && . /etc/rc.status

if [ "$DISTRIBUTION" = "suse" ] ; then
  echo_success() {
    rc_status -v
  }
  echo_failure() {
    rc_status -v
  }
  success() {
    echo_success
  }
  failure() {
    echo_success
  }
elif [ "$DISTRIBUTION" = "debian" ] ; then
  echo_success() {
    echo ok
  }
  echo_failure() {
    echo failed
  }
  success() {
    echo_success
  }
  failure() {
    echo_success
  }
fi

start() {
  ulimit -n 65536
  ulimit -s 10240
  ulimit -c unlimited
  mkdir -p ${LOGDIRECTORY}
  if ! -f $PIDFILE > /dev/null 2>&1
    then
        echo -n "Starting ${DAEMON}: "
        touch $PIDFILE
        daemon -u $USER --pidfile $PIDFILE --stdout=$LOGFILE --stderr=$LOGFILE -- ${DAEMON}
        RETVAL=$?
        [ $RETVAL -eq 0 ] && echo_success
        [ $RETVAL -ne 0 ] && echo_failure
            echo
        return $RETVAL
    else
        echo "Daemon is already running"
  fi
}

stop() {
      echo -n "Stopping ${DAEMON}"
      echo ""
      pkill -TERM -P $(<"$PIDFILE")
      rm -f $PIDFILE
}

reload() {
  stop
  start
}

restart() {
  stop
  start
}

case "$1" in
start)
  start
  ;;

stop)
  stop
  ;;

reload)
  reload
  ;;

restart)
  restart
  ;;

*)
  echo $"Usage: $0 {start|stop|reload|restart}"
  exit 1
esac

exit $?
