#!/bin/sh
#
# $FreeBSD: tags/RELEASE_9_1_0/net-mgmt/nagios/files/nagios.in 300897 2012-07-14 14:29:18Z beat $
#

# PROVIDE: nagios
# REQUIRE: LOGIN
# KEYWORD: shutdown

#
# Add the following lines to /etc/rc.conf to enable nagios:
# nagios_enable (bool):    Set to "NO" by default.
#                          Set it to "YES" to enable nagios.
# nagios_precache (bool):  Set to "NO" by default.
#                          Set it to "YES" to enable pre-caching.
# nagios_flags (str):      Set to "" by default.
# nagios_configfile (str): Set to "/usr/local/etc/nagios/nagios.cfg" by default.
#

. /etc/rc.subr

name="nagios"
rcvar=nagios_enable

command="/usr/local/bin/nagios"
command_args="-d"
extra_commands="reload configtest"
pidfile="/var/spool/nagios/nagios.lock"
nagios_user="nagios"

start_precmd="start_precmd"
stop_postcmd="stop_postcmd"
restart_precmd="nagios_checkconfig"
reload_precmd="reload_precmd"
configtest_cmd="nagios_checkconfig"
sig_reload=HUP

load_rc_config "${name}"

[ -z "${nagios_enable}" ]       && nagios_enable="NO"
[ -z "${nagios_configfile}" ]   && nagios_configfile="/usr/local/etc/nagios/nagios.cfg"
[ -z "${nagios_precache}" ]     && nagios_precache="NO"

required_files="${nagios_configfile}"
command_args="${command_args} ${nagios_configfile}"

nagios_cacheconfig() {
  if ! checkyesno nagios_precache; then
    return 0
  fi

  echo -n "Pre-Caching nagios configuration: "
  ${command} -pv ${nagios_configfile} 2>&1 >/dev/null
  if [ $? != 0 ]; then
    echo "FAILED"
    ${command} -v ${nagios_configfile}
    return 1
  else
    command_args="-u -x ${command_args}"
    echo "OK"
  fi
}

nagios_checkconfig() {
  echo -n "Performing sanity check of nagios configuration: "
  ${command} -v ${nagios_configfile} 2>&1 >/dev/null
  if [ $? != 0 ]; then
    echo "FAILED"
    ${command} -v ${nagios_configfile}
    return 1
  else
    echo "OK"
  fi
}

reload_precmd() {
  if ! nagios_checkconfig; then
    return 1
  fi

  if ! nagios_cacheconfig; then
    return 1
  fi
}

start_precmd() {
  if ! nagios_checkconfig; then
    return 1
  fi

  if ! nagios_cacheconfig; then
    return 1
  fi

  su -m "${nagios_user}" -c "touch \"/var/spool/nagios/nagios.log\" \"/var/spool/nagios/status.sav\""
  rm -f "/var/spool/nagios/rw/nagios.cmd"
}

stop_postcmd() {
  rm -f "/var/spool/nagios/nagios.tmp" "/var/spool/nagios/rw/nagios.cmd"
}

run_rc_command "$1"
