#!/bin/sh
# -*- sh -*-
#
# Plugin to monitor NTP time offset.
#  Loosely based on ntp_ plugin, but reworked to shell.
#
# Parameters understood:
#
# 	config   (required)
# 	autoconf (optional - used by munin-node-configure)
#
#       [ntp_*]
#           env.nodelay 1       - Set to 1 to remove delay
#
# Magic markers - optional - used by installation scripts and
# munin-node-configure:
#
#%# family=auto
#%# capabilities=autoconf

do_autoconf () {
    ntpq -c help >/dev/null 2>&1 || { echo 'no (no ntpq program)'; exit 1; }
    
    case "$(ntpq -n -p 2>/dev/null | wc -l)" in
	0)
            echo 'no (unable to list peers)'
	    exit 1
	    ;;
    	1|2)
	    echo 'no (no peers?)'
	    exit 1
	    ;;
	*)
	    echo yes
	    exit 0
	    ;;
    esac
}

do_config () {
    syspeer="$(ntpq -n -p | grep '^[*o]')"

    set - $syspeer

    peer=$1
    # Times in ms, therefore cdefs to divide to obtain seconds
    # delay=$8
    # offset=$9
    # jitter=$10

    cat <<EOF
graph_title NTP timing statistics for system peer
graph_args --base 1000 --vertical-label seconds --lower-limit 0
graph_category time
delay.label Delay
delay.draw LINE2
delay.cdef delay,1000,/
offset.label Offset
offset.draw LINE2
offset.cdef offset,1000,/
jitter.label Jitter
jitter.draw LINE2
jitter.cdef jitter,1000,/
info Currently our peer is $peer.  Please refer to ntp docs and ntpc docs for further explanations of these numbers.
EOF
    case $nodelay in
	1) echo "delay.graph no";;
    esac
}

do_ () {
    # Fetch operation
    syspeer="$(ntpq -n -p | grep '^[*o]')"

    set - $syspeer

    # peer=$1
    # Times in ms, therefore cdefs to divide to obtain seconds
    shift # Avoid having to use $10
    delay=$7
    offset=$8
    jitter=$9
    cat <<EOF
delay.value $delay
offset.value $offset
jitter.value $jitter
EOF
}

case $1 in
    autoconf|config|'')
       do_$1
       exit $?
       ;;
    *)
       echo "Don't know how to do that" >&2
       exit 1
       ;;
esac

echo 'What am I doing here?' >&2
exit 1

# vim:syntax=sh
