#!/bin/bash 
#
# check_ntp_chrony
#
# Author 		: nohaj
# Contact 		: johan@slashroot.fr
# Date 			: 20/05/15
# Version 		: 1.0
# Description	: Check localhost NTP synchronization through chrony
# Notes 		: Designed to be used by Nagios/Shinken from NRPE

#
# Variables and checks
#

# Defaults threshold
warning=5
critical=10

# We check if chrony is there
if [ ! -f /usr/bin/chronyc ] ; then
	echo "CRITICAL: Chrony is not installed"
	exit 2
fi

# We check that chronyd is up and running
if ( ! systemctl is-active chronyd &> /dev/null ) || ( ! pgrep chronyd &> /dev/null ) ; then
	echo "CRITICAL: Chronyd is not running"
	exit 2
fi

#
# Usage
#

usage(){
	echo ""
	echo "Usage : check_ntp_chrony [-w WARNING] [-c CRITICAL]"
	echo ""
	echo "OPTIONS :"
	echo "   -h     Print help"
	echo "   -w     Warning threshold (default : $warning)"
	echo "   -c     Critical threshold (default : $critical)"
	echo ""
}

#
# Getopts
#

while getopts ":h:w:c:*" opt; do
	case $opt in
		w)
			warning="$OPTARG"
			;;
		c)
			critical="$OPTARG"
			;;
		h)
			usage
			exit 3
			;;
		\?)
			usage
			exit 3
			;;
		*)
			usage
			exit 3
			;;
	esac
done

#
# Let's get the party started
#

# We gather the tracking informations
chronyc=`/usr/bin/chronyc tracking`

# We check the stratum level
stratum=`echo "$chronyc" | grep Stratum | awk '{print $3}'`
if [ $stratum -eq 0 ] ; then
	echo "CRITICAL: NTP is desynchronized (stratum 0)"
	exit 2
fi

# We check the offset
offset_full=`echo "$chronyc" | grep "System time"`
offset=`echo $offset_full | awk '{print $4}'`
offset_cut=`echo $offset | cut -d "." -f1`
speed=`echo $offset_full | awk '{print $6}'`

if [ $speed == "fast" ] ; then
	speed=""
elif [ $speed == "slow" ] ; then
	speed="-"
else
	echo "UNKNOWN: Status of system time is not fast or slow"
	exit 3
fi

if [ $offset_cut -ge $warning ] ; then
	if [ $offset_cut -ge $critical ] ; then
		echo "CRITICAL: Offset "$speed""$offset secs"|offset="$speed""$offset"s;$warning;$critical"
		exit 2
	else
		echo "WARNING: Offset "$speed""$offset secs"|offset="$speed""$offset"s;$warning;$critical"
		exit 1
	fi
else
	echo "OK: Offset "$speed""$offset secs"|offset="$speed""$offset"s;$warning;$critical"
	exit 0
fi

