#!/bin/bash
#
# Script to parse Chrony Tracking Output
#
# Parameters understood:
#
#       config   (required)
#       autoconf (optional - used by munin-config)
#
# $log$
# Revision 0.1 2008/08/23 13:06:00 joti
# First version only chronyc tracking, autodetection included.
#
# Revision 0.2 2008/10/11 16:09:00 joti
# Added scaling of other values to match with frequency, added more description to fields
#
# Revision 0.3 2014/02/16 zjttoefs
# reduce forking by using awk
# do not limit output precision
# add stratum monitoring
# detect slow/fast time or freqency and adjust sign of value accordingly
# remove commented out code
#
# Magic markers (optional - used by munin-config and installation scripts):
#
#%# family=auto
#%# capabilities=autoconf

#Modify this to fit other chronyc path
CHRONYC=/usr/bin/chronyc

#Frequency has extremely higher values than other. Therefore they are fitted by scaling. Adjust the factors here
fieldfactors="1 1000 1 100 100 1000 1000"
#fieldfactors="1 1000000 0.1 100 10 10 10"
fields="stratum systime frequency residualfreq skew rootdelay rootdispersion"
fieldnames="Stratum (=System Time (seconds,x=Frequency (ppm,x=Residual Freq (ppm,x=Skew (ppm,x=Root delay(seconds,x=Root dispersion (seconds,x"

if [ "$1" = "autoconf" ]; then
	if [ -f "$CHRONYC" ]; then 
		echo yes
		exit 0
	else
		echo "no (no $CHRONYC)"
		exit 1
	fi
fi

if [ "$1" = "config" ]; then
        echo 'graph_title Chrony Tracking Stats'
        echo 'graph_args --base 1000 -l 0'
        echo 'units (seconds,ppm)'
	echo 'graph_category time'    
		i=0
		for a in $fields ; do
			i=$(expr $i + 1);
			word=`echo $fieldnames | cut -f $i -d '='`;
			factor=`echo $fieldfactors | cut -f $i -d ' '`;
			echo "$a.label $word$factor)";
			echo "$a.type GAUGE";
		done
        exit 0
fi

# remove non-needed output lines, remove labels, rescale and label values while detecting slow/fast keywords
chronyc tracking | sed -e 1d -e 3d -e "s/.*://" | \
	awk -v FAC="$fieldfactors" -v NAM="$fields" \
	'BEGIN { split(FAC,factors," "); split(NAM,names," "); } 
	{ /slow/ ? SIGN=-1 : SIGN=1 ; print names[NR]".value ",SIGN*$1*factors[NR]}' 
