#!/bin/sh
#

OUT=/etc/nagios/checkcommands.cfg

cat > $OUT <<EOT
# This file was autogenerated on `date` and
# should not be manually altered. Use update-nagios to
# build this file. If you need to add a command specification, edit
# /etc/nagios/checkcommands.cfg
# If you need to change the configuration of a command, it's better
# to look in /usr/share/{nagios,netsaint}/pluginconfig/*.cfg and copy
# the command to /etc/nagios/checkcommands.cfg and give it a new name.

EOT

FOUND_PLUGINS=false

# Automatically convert netsaint plugin configuration files to a format
# understood by nagios.  Assumes the incoming file contains lines like:
#
# command[ssh_disk]=/usr/lib/nagios/plugins/check_by_ssh -H $HOSTADDRESS$ -C '/usr/lib/nagios/plugins/check_disk -w 95% -c 85% -p $ARG1$'
#
for f in /usr/share/nagios/pluginconfig/*.cfg /usr/share/netsaint/pluginconfig/*.cfg; do
  if [ -f $f ] ; then # to avoid getting * literally if no match
    echo "# Included from $f" >>$OUT

    if echo $f | grep -q '/netsaint/'; then
	# --- Netsaint plugin
	perl -ne 'if (/^command\[([^]]*)\]=(.*)$/) { 
                print "# '"'"'$1'"'"' command definition\n";
	        print "define command {\n";
	        print "\t\tcommand_name\t$1\n";
	        print "\t\tcommand_line\t$2\n";
	        print "\t\t}\n"; 
	      } else { print; }' $f >>$OUT
	echo >>$OUT
	FOUND_PLUGINS=true
    else
	# --- Nagios plugin
	echo "# Included from $f" >>$OUT
	cat $f >>$OUT
	echo >>$OUT
	FOUND_PLUGINS=true
    fi
  fi
done

if $FOUND_PLUGINS; then
	if [ -x /etc/init.d/nagios -a "$1" != "--no-reload" ] ; then	
		/etc/init.d/nagios reload
    fi
else
    echo "Created an empty checkcommands.cfg file, because no plugin configs"
    echo "found in /usr/share/{nagios,netsaint}/pluginconfig. Won't reload nagios."
    exit 0
fi
