#!/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 -f ../scotty ; then
      exec ../scotty -nf $0 $*
    else
      exec scotty -nf $0 $*
    fi
}

##
## Simply print the rstat information given by an rstatd.
##

##
## Compute the diff between two rstat calls.
##

proc rstat_diff {l1 l2 period} {
    set len [llength $l1]
    set res ""
    for {set i "0"} {$i<$len} {incr i} {
        set el1 [lindex $l1 $i]
        set el2 [lindex $l2 $i]
        set tmp [lindex $el1 2]
        if {[lindex $el1 1]=="Counter"} {
            set tmp [expr {[lindex $el1 2]-[lindex $el2 2]}]
	    set tmp [expr {"$tmp.0" / $period}]
	}	
        if {[lindex $el1 1]=="Gauge"} {
            set tmp [expr {[lindex $el1 2]/256.0}]
        }
        lappend res [format "%-12s %-12s %16.3f" \
		     [lindex $el1 0] [lindex $el1 1] $tmp]
    }
    return $res
}

proc rstat {host period} {
    set stat [sunrpc stat $host]
    after [expr $period * 1000]
    set newstat [sunrpc stat $host]
    set res ""
    foreach s [rstat_diff $newstat $stat $period] { lappend res $s }
    return $res
}

##
## Check the commandline and start reporting.
##

proc usage {} {
    puts stderr "usage: rstat hostname interval \[iterations\]"
    exit
}

if { !([llength $argv] == 2 || [llength $argv] == 3)} { usage } else {
    set ip [lindex $argv 0]
    set interval [lindex $argv 1]
    set interval [expr {$interval <1 ? 1 : $interval}]
    if {[llength $argv] == 3} {
        set iterations [lindex $argv 2]
    } else {
        set iterations -1
    }
    while { $iterations != 0 } {
	if {[catch {rstat $ip $interval} result]} {
	    puts "rstat: $result"
	    return
	}
	foreach elem $result {
	    puts $elem
	}
	puts ""
	if { $iterations > 0 } { incr iterations -1 }
    }
}

exit
