#!/bin/sh
#
# Generate graphs of ping information for use by the FChart gkrellm plugin.
#
# Usage:
#
USAGE='Usage: pingtimer [-b base] [-i interval] host ...'
#
# Options:
#
#   -i	Specify the interval between ping attempts (default 1).
#   -b	Specify the base pathname of output files (default /tmp/pingtimer).
#
# Output files:
#
#    $BASE.tmp	Temporary file used in generating final output
#    $BASE.txt	Ping information
#
# Each host given is repeatedly pinged in turn.  Nothing is done to
# protect against relatively long timeout (10 seconds) from failed
# pings.  The ping times (expressed in microseconds) are written to
# the chart file in host order.  Since FChart will only plot three
# values, only the first three hosts are meaningful.
#
# The alert level of FChart is always NORMAL.  Only one string is
# added to the chart: $0 is the maximum of the three ping times,
# expressed in milliseconds.
#

BASE=/tmp/pingtimer
INTERVAL=1

while [ $# -gt 0 ]
do
    case "$1" in
	-b)
	    BASE="$2"
	    shift
	    ;;
	-i)
	    INTERVAL="$2"
	    shift
	    ;;
	--)
	    shift
	    break
	    ;;
	-*)
	    echo "$USAGE" 1>&2
	    exit 2
	    ;;
	*)
	    break
	    ;;
    esac
    shift
done

if [ $# -eq 0 ]
then
    echo "$USAGE" 1>&2
    exit 2
fi

while sleep $INTERVAL
do
    for i
    do
	ping -c 1 $i \
	  | sed -n '/^64 bytes from/s/^.*time=\([0-9.]*\).*$/\1/p' \
	  | awk '{print int($1 * 1000 + 0.5)}'
    done \
      | tr \\012 ' ' \
      > "$BASE".tmp
    echo '' >> "$BASE".tmp
    max=`tr ' ' \\\\012 < "$BASE".tmp \
      | sort -rn | grep -v '^$' | head -1`
    echo 'NORMAL' >> "$BASE".tmp
    echo $max | awk '{printf "%.3f\n", $1 / 1000}' >> "$BASE".tmp
    cp "$BASE".tmp "$BASE".txt
done
