#!/bin/sh

# Set a default path
PATH="/usr/bin:/bin"

# This is where we write to Nagios command pipe
# Make sure it's writeable (follow Nagios plugin exit code API)
commandfile="/usr/local/nagios/var/rw/nagios.cmd"
if [ ! -w "$commandfile" ]; then
  echo "ERROR: Cannot write to $commandfile"
  exit 2
fi

# Send to Nagios
send_nagios() {
  now=`date +%s`
  /bin/printf "[%lu] $*\n" $now > $commandfile
}

# Stop executing service checks
stop_engine() {
  send_nagios "STOP_EXECUTING_SVC_CHECKS"
  send_nagios "STOP_EXECUTING_HOST_CHECKS"
  send_nagios "STOP_ACCEPTING_PASSIVE_SVC_CHECKS"
  send_nagios "STOP_ACCEPTING_PASSIVE_HOST_CHECKS"
  send_nagios "DISABLE_EVENT_HANDLERS"
  send_nagios "DISABLE_NOTIFICATIONS"
  send_nagios "DISABLE_FLAP_DETECTION"
  send_nagios "DISABLE_PERFORMANCE_DATA"
}

# Start the monitoring engine
start_engine() {
  send_nagios "START_ACCEPTING_PASSIVE_HOST_CHECKS"
  send_nagios "START_ACCEPTING_PASSIVE_SVC_CHECKS"
  send_nagios "START_EXECUTING_HOST_CHECKS"
  send_nagios "START_EXECUTING_SVC_CHECKS"
  send_nagios "ENABLE_EVENT_HANDLERS"
  send_nagios "ENABLE_NOTIFICATIONS"
  send_nagios "ENABLE_FLAP_DETECTION"
  send_nagios "ENABLE_PERFORMANCE_DATA"
}

while [ -n "$1" ]; do
  case "$1" in
    start) start_engine; shift 1;;
    stop) stop_engine; shift 1;;
    *) shift 1;;
  esac
done
