#! /bin/bash
# © 2011 Heiko Schlittermann <hs@schlittermann.de>
# source: https://ssl.schlittermann.de/hg/check-by-nsca

set -e

unset ${!LC_*} LANG
export LC_ALL=C
ME=$(basename $0)
TAB=$'\x09'

function send()       { send_nsca "$@"; }
function debug_send() { echo "CMDLINE: $@"; sed 's/\t/<<TAB>>/g'; }
send=send             # changed by option


# read defaults, if exist
test -f /etc/defaults/$ME \
    && source /etc/defaults/$ME

hostname=$(hostname -f)
svcname=-
nsca_host=
nsca_port=

tmp=$(getopt -n $0 -o hH:S:p:d \
    -l help,hostname:,servicename:,nsca-host:,nsca-port:,debug \
    -- "$@") || exit 2
eval set -- "$tmp"

while true; do
    opt="$1"; shift
    case "$opt" in
        -H|--hostname)  hostname="$1"; shift;;
        -S|--svcname)   svcname="$1"; shift;;
           --nsca-host) nsca_host="$1"; shift;;
        -p|--nsca-port) nsca_port="$1"; shift;;
        -h|--help)      cat <<_USAGE
Usage: $ME [options] -- {test} [test-options]
       -H|--hostname    Hostname to be sent along the result ($hostname).
       -S|--servicename Servicename to be sent along the result.
                        Use "" to mark a host check.
                        Use "-" (the default) to have the servicename guessed 
                        from the test output (the first word).
       --nsca-host      Destination host ($nsca_host)
       --nsca-port      Destination port ($nsca_port)
_USAGE
                        exit 0;;
       -d|--debug)      send="debug_$send";;
        --)     break;;
    esac

done

rc=0
output=$("$@") || rc=$?

test "$svcname" = "-" && svcname="${output%% *}"
svcname="${svcname:+$TAB$svcname}"

echo "$hostname$svcname$TAB$rc$TAB$output" \
        | $send -H "$nsca_host" ${nsca_port:+-p $nsca_port}

# vim:sts=4 sw=4 aw ai sm et:
