#!/bin/bash

# check_time_deviation_via_http.sh
#
# This method uses the HTTP header of a target webserver to measure the system
# time deviation of the target system to the local host.
#
# Copyright (C) 2007-2012 Robert Marxreiter <rmarxreiter@web.de>
#
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0

[ -z $4 ] && {
	echo "usage: $0 <url> <repetitions> <warning threshold> <critical threshold>";
	exit 3;
}


url="$1";
repetitions=$2;
warning=$3;
critical=$4;

minabs="";
for ((x=0; x < $repetitions; x++)); do
	date="$(curl -s -k -I "$url" | sed -rn "s/Date: (.+)/\1/p")";
	[ -z "$date" ] && {
		echo "could not measure time deviation via HTTP(S)";
		exit 3;
	}
	deviation=$(date +%s -d "$date - $(date +%s) seconds");
	[ $deviation -lt 0 ] && ((abs = -deviation)) || abs=$deviation;
	if [ -z "$minabs" ] || [ $abs -lt $minabs ]; then
		minabs=$abs;
		mindeviation=$deviation;
	fi;
done;
if [ $minabs -gt $critical ]; then
	echo "CRITICAL: time deviation $mindeviation is more than $critical seconds off|time_deviation=$mindeviation";
	exit 2;
elif [ $minabs -gt $warning ]; then
	echo "WARNING: time deviation $mindeviation is more than $warning (but not more than $critical) seconds off|time_deviation=$mindeviation";
	exit 1;
else
	echo "OK: time deviation $mindeviation is within the range of $warning seconds|time_deviation=$mindeviation";
	exit 0;
fi;
