#!/bin/sh
#
# Author: Petter Reinholdtsen

set -e

nodes=/usr/sbin/sitesummary-nodes
nagiosopts=""

# Specifies where to save the automatically generated nagios
# configuration.  Add NAGIOSCFG="/etc/icinga/sitesummary.cfg" to
# /etc/default/icinga to get Icinga to use this automatically
# generated configuration
NAGIOSDIR=/var/lib/sitesummary

if [ -f /etc/sitesummary/collector.cfg ] ; then
   . /etc/sitesummary/collector.cfg
fi

# The storage area is not configurable, because too many scripts have
# it hardcoded
entriesdir=/var/lib/sitesummary/entries

generate_nagios_config() {
    (
	$nodes -n $nagiosopts

	if [ -f $NAGIOSDIR/nagios-generated.cfg.post ] ; then
	    cat $NAGIOSDIR/nagios-generated.cfg.post
	fi

	true
    ) > $NAGIOSDIR/nagios-generated.cfg.new && \
        chmod a+r $NAGIOSDIR/nagios-generated.cfg.new
    if [ ! -s $NAGIOSDIR/nagios-generated.cfg.new ] || \
       cmp -s $NAGIOSDIR/nagios-generated.cfg.new \
              $NAGIOSDIR/nagios-generated.cfg
    then
	rm $NAGIOSDIR/nagios-generated.cfg.new
	false
    else
        mv $NAGIOSDIR/nagios-generated.cfg.new $NAGIOSDIR/nagios-generated.cfg
	true
    fi
}

# Only enable if icinga and sitesummary is installed.
if [ -f /etc/init.d/icinga ] && [ -x $nodes ]; then
    # Only reload icinga if the configuration changed
    if generate_nagios_config ; then
    # subshell to avoid passing all variables from
    # /etc/default/icinga to other parts of this script
    (
	if [ -r /etc/default/icinga ] ; then
	    . /etc/default/icinga
	fi
	# Only reload icinga if the sitesummary config is the active
	# one and icinga is currently running.
	if [ /etc/icinga/objects/sitesummary.cfg = "$NAGIOSCFG" ] && \
	    service icinga status >/dev/null ; then
	    service icinga reload >/dev/null
	fi
    )
    fi
fi
