#!/bin/sh
# Tcl sees the next lines as an assignment to variable `kludge'.
# For sh, the two shifts cancel the effect of the set, and then we
# run scotty on this script.

set kludge { $*
    shift
    shift
    if test -x ../scotty ; then
      exec ../scotty -nf $0 $*
    else
      exec scotty -nf $0 $*
    fi
}

#
# Send a udp datagram to the echo port of the destionation host
# and wait for an answer. Get the time using tcl's time command.
#

proc udp_ping {host} {

    global timeout

    set file [udp open]
    set error 0

    set result [time {
        if {[catch {udp send $file $host 7 "hi"}]} {
	    set error 1
        } elseif {[select $file {} {} $timeout] != ""} { 
	    catch {udp receive $file}
	} else {
	    set error 1
	}
    }]

    set result [expr {$error ? -1 : [lindex $result 0]/1000}]

    udp close $file

    return [list $host $result]
}

proc usage {} {
    puts stderr "usage: uiping \[-t time\] hostnames"
    exit
}

##
## Parse the command line options.
##

set timeout 5
catch {icmp -timeout $timeout}

if {$argc==0} usage

while {$argv!=""} {
    set argc [llength $argv]
    case [lindex $argv 0] in {
        {-t} {
            if {$argc == 1} usage
	    set timeout [lindex $argv 1]
            if {[catch {icmp -timeout [lindex $argv 1]}]} usage
            set argv [lrange $argv 2 end]
        }
        {default} break
    }
}

if {[llength $argv] == 0} usage

while {1} {
    foreach arg $argv {
        set urtt [lindex [udp_ping $arg] 1]
	puts -nonewline [format "%-16s " $arg]
	if {$urtt > 0} {
	    puts -nonewline [format "%5d ms " $urtt]
	} else {
	    puts -nonewline [format "  *** ms "]
	}
	set irtt [lindex [join [icmp $arg]] 1]
	if {$irtt > 0} {
            puts [format "%5d ms" $irtt]
        } else {
            puts "  *** ms"
        }
    }
    sleep 1
}

exit
