#!/bin/bash
#
# __copy1__
# __copy2__
#
# checks for net lag (ping round time) on interface(s)
#
# returns 0 if ALL the interfaces are below the trigger value
# returns 1 if at least one of them are over the trigger value
# returns 255 on syntax error
#
# if an interface is down, returns 0, if option --mandatory
# is used returns 1 immediatly (counts as infinite lag)
#
# you pass the interface name FOR LOGGING PURPOUSE ONLY,
# the ping command routes packet via the local routing
# table, as usual, so you need to use the proper address 
#
CMD=${CMD:-"$0"}
DEBUG=${DEBUG:-"false"}

usage()
{
	echo "usage: $0 [--mandatory] interface value address  {int2 value2 addr2 ...}" >&2
	exit 255
}

do_check_interfaces()
{
	local int=
	local trig=
	local addr=
	local ping=
	local trig_m=
	local ping_m=

	while [ $# != 0 ]
	do
		[ $# -lt 3 ] && {
			usage
			return 255
		}
		int=$1 ; trig=$2 ; addr=$3 ; shift 3

		echo -en "testing ping on $int -> $addr		" >&2

		ping=`ping -n -q -c 1 -w 5 $addr` || {
			echo "(down)" >&2
			$F_MANDATORY && return 1
			continue
		}

		#rtt min/avg/max/mdev = 0.333/0.333/0.333/0.000 ms
		ping=`echo "$ping" | tail -1 | sed -e 's/.* = [0-9][0-9.]*\///' -e 's#/.*##'`
		ping_m=`echo "$ping * 1000 / 1" | bc`
		trig_m=`echo "$trig * 1000 / 1" | bc`


		if [ $ping_m -ge $trig_m ]
		then
			echo "LAG  max=$trig ($trig_m)   actual=$ping ($ping_m)  " >&2
			logger -s -t $CMD "lag detected on $int  max=$trig actual=$ping"
			return 1
		else
			echo "     max=$trig ($trig_m)   actual=$ping ($ping_m)  " >&2
		fi
	done
}


F_MANDATORY=false

case "$1" in
    --mandatory)	F_MANDATORY=true; shift ;;
    -*|"")		usage ;;
esac

do_check_interfaces "$@"
exit $?
