#!/bin/sh
# /etc/init.d/nxlog: start the nxlog daemon.

### BEGIN INIT INFO
# Provides:             nxlog
# Required-Start:       $remote_fs
# Required-Stop:        $remote_fs
# Should-Start:         $network $named $time
# Should-Stop:          $network $named $time
# Default-Start:        2 3 4 5
# Default-Stop:         0 1 6
# Short-Description:    logging daemon
### END INIT INFO

PATH=/opt/nxlog/libexec:/bin:/usr/bin:/sbin:/usr/sbin
BASE=/opt/nxlog
#OPENSSL_CONF=/dev/null
#export OPENSSL_CONF

pidfile=$BASE/var/run/nxlog/nxlog.pid
nxlog=$BASE/bin/nxlog
conf=/opt/nxlog/etc/nxlog.conf

# NOTE: init scripts clear all variables except LANG, TERM and PATH.
# we need to read variables from the configuration file to properly
# set permissions.

if [ -f $conf ]; then
  NXLOG_GROUP=$(awk '/Group/ {print $2}' $conf)
  NXLOG_USER=$(awk '/User/ {print $2}' $conf)
else
  NXLOG_GROUP=nxlog
  NXLOG_USER=nxlog
fi

test -f $nxlog || exit 0

. /lib/lsb/init-functions

case "$1" in
  start)
    if [ -f $pidfile ]; then
      log_begin_msg "nxlog is already running"
      log_end_msg $?
    else
      log_begin_msg "starting nxlog daemon"
      if ! [ -d $BASE/var/run/nxlog ]; then
        mkdir $BASE/var/run/nxlog
      fi
      chown $NXLOG_USER:$NXLOG_GROUP $BASE/var/run/nxlog
      chmod 1770 $BASE/var/run/nxlog
      $nxlog
      log_end_msg $?
    fi
    ;;
  stop)
    if [ -f $pidfile ]; then
      log_begin_msg "stopping nxlog daemon"
      $nxlog -s >/dev/null
      log_end_msg 0
    else
      log_begin_msg "nxlog is not running"
      log_end_msg 0
    fi
    ;;
  reload)
    if [ -f $pidfile ]; then
      log_begin_msg "reloading nxlog daemon"
      $nxlog -r >/dev/null
      log_end_msg $?
    else
      $0 start
    fi
    ;;
  status)
    status_of_proc -p $pidfile $nxlog nxlog  && exit 0 || exit $?
    RETVAL=$?
    ;;
  restart|force-reload)
    if [ -f $pidfile ]; then
      log_begin_msg "restarting nxlog daemon"
      $nxlog -s >/dev/null
      $nxlog >/dev/null
      log_end_msg $?
    else
      $0 start
    fi
    ;;
  *)
    log_success_msg "Usage: /etc/init.d/nxlog {start|stop|reload|status|restart|force-reload}"
    exit 1
esac

exit 0
