#!/bin/sh
# $Id: nagios-notify 9899 2008-10-11 15:00:04Z glen $
#
# Template based Nagios notify script.
# Requires: awk, base64 (coreutils)
#
# Author: Elan Ruusamäe <glen@pld-linux.org>
# License: Same as Nagios (GPL v2)
#

templatedir='/etc/nagios/templates'
export NAGIOS_DATADIR='/usr/share/nagios'
prog="${0##*/}"

# Substutute Nagios $VAR$-s (which are exported to environment by Nagios) inside template.
template_subst() {
	local tmpl="$1"
	awk '
	# escape string for shell arg
	function escape_shell_arg(string) {
		q = sprintf("%c", 39);
		qq = "\"";
		s = q qq q qq q;
		gsub(q, s, string);
		return q string q
	}

	# base64 encode a file
	function base64(file) {
		cmd = "base64 " file;
		out = ""
		while ((cmd | getline) > 0) {
			out = out $0;
		}
		close(cmd);
		return out;
	}

	# base64 encode a string
	function base64_string(data) {
		# if i knew how to make two way pipes, i would do that here
		cmd = "echo -n " escape_shell_arg(data) " | base64";
		out = ""
		while ((cmd | getline) > 0) {
			out = out $0;
		}
		close(cmd);
		return out;
	}

	# encode email header as rfc2047 (using base64 encoding)
	function encode_mime_header(charset, data) {
		return "=?" charset "?b?" base64_string(data) "?="
	}

	{
		# replace environ variables
		for (var in ENVIRON) {
			if (substr(var, 1, length("NAGIOS_")) == "NAGIOS_") {
				val = ENVIRON[var];
				var = substr(var, 1 + length("NAGIOS_"));
				gsub("\$" var "\$", val);
			}
		}

		# $(base64:/path/to/file)
		if (match($0, /\$\(base64:(.*)\)/)) {
			pos = length("$(base64:")
			file = substr($0, RSTART + pos, RLENGTH - pos - 1);
			left = substr($0, 0, RSTART);
			right = substr($0, RSTART + RLENGTH);
			$0 = left base64(file) right;
		}

		# $(encode_mime_header:CHARSET,DATA)
		if (match($0, /\$\(encode_mime_header:([^,]*,.*)\)/)) {
			pos = length("$(encode_mime_header:")
			params = substr($0, RSTART + pos, RLENGTH - pos - 1);
			left = substr($0, 0, RSTART);
			right = substr($0, RSTART + RLENGTH);
			charset = substr(params, 1, index(params, ",") - 1)
			data = substr(params, index(params, ",") + 1)
			$0 = left encode_mime_header(charset, data) right;
		}

		# print out
		print
	}
	' $tmpl
}


if [ "${NAGIOS_STATUSDATAFILE+set}" = set ]; then
	NAGIOS_STATUSDATAFILE=${NAGIOS_STATUSDATAFILE:-/var/lib/nagios/status.dat}
else
	echo >&2 "$prog: This program must be ran from Nagios."
	exit 1
fi

# extract Nagios version from status file
export NAGIOS_VERSION=$(awk -F= '/version=/{print $2}' $NAGIOS_STATUSDATAFILE)

tmpl="$templatedir/$1.tmpl"
if [ ! -f "$tmpl" ]; then
	echo >&2 "$prog: template '$tmpl' can not be found!"
	exit 1
fi

template_subst "$tmpl"
