#!/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
#
# 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 factor here
FACTOR=1000
#fieldfactors="1000 1 1000 100 1000 1000"
fieldfactors="1000 1 100 100 1000 1000"
#Fields to catch and graph, second line is friendly name
fields="systime frequency residualfreq skew rootdelay rootdispersion"
fieldnames="System Time (seconds,x=Frequency (seconds,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 'graph_vlabel seconds / ${graph_period}'
        echo 'units (seconds,ppm)'
	#echo 'graph_total total'
	echo 'graph_category NTP'    
		i=0
		for a in $fields ; do
			i=$(expr $i + 1);
			#echo "i=$i"
			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 superflous whitespace (hinders cut), remove non-needed output lines, remove more space,cut out final result value, scale values to factor if needed, output values in munin-required format
j=0
chronyc tracking  |  \
	sed "s/  */ /g" | \
	sed "1,3d" | \
#	grep -v "Frequency" | \
	sed "s/ : /:/g" | \
	cut -f 2 -d ':' | \
	cut -f 1 -d ' ' | \
	while read LINE; do
		j=$(expr $j + 1);
		measure=`echo $fields | cut -f $j -d ' '`;
		factor=`echo $fieldfactors | cut -f $j -d ' '`;
		echo -en "$measure.value ";
#		if [ "$measure" = "frequency" ]; then 
			#measure is frequency do not enlarge numbers
#			echo $LINE | xargs printf "%1.2f";
#		else
			#measure is not frequency, enlarge numbers to make them showable together with frequency
			echo $LINE*$factor | bc | xargs printf "%1.2f";
#		fi
		#echo $LINE*100 | bc | xargs printf "%1.2f";
		echo;
	done

