#!/bin/sh
# the next line restarts using scotty -*- tcl -*- \
exec scotty2.1.11 "$0" "$@"

package require Tnm 2.1

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

proc rstat {host interval} {
    set stat [join [sunrpc stat $host]]
    after [expr $interval * 1000]
    set newstat [join [sunrpc stat $host]]

    foreach {n1 t1 v1} $stat {n2 t2 v2} $newstat {
	switch $t1 {
	    Counter {
		set r($n2) [expr int(double($v2 - $v1) / $interval)]
	    }
	    Gauge {
		set r($n2) [expr $v2/256.0]
	    }
	    default {
		set r($n2) $v2
	    }
	    
	}
    }

    puts [format "%2.2f %2.2f %2.2f  %3d %3d %3d %5d %5d %3d%3d%3d%3d %4d%4d%4d%4d %4d %4d" \
	    $r(avenrun_0) $r(avenrun_1) $r(avenrun_2) \
	    [expr $r(cp_user) + $r(cp_nice)] $r(cp_system) $r(cp_idle) \
	    $r(v_swtch) $r(v_intr) \
	    $r(dk_xfer_0) $r(dk_xfer_1) $r(dk_xfer_2) $r(dk_xfer_3) \
	    $r(v_pgpgin) $r(v_pgpgout) $r(v_pswpin) $r(v_pswpout) \
	    $r(if_ipackets) $r(if_opackets) \
	 ]
}

##
## 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
    }
    puts "    load            cpu         traps        disk         paging       netstat"
    puts "                 us  sy  id    in    cs  d0 d1 d2 d3   pi  po  si  so   in  out"
    while { $iterations != 0 } {
	if {[catch {rstat $ip $interval} result]} {
	    puts "rstat: $result"
	    return
	}
	if { $iterations > 0 } { incr iterations -1 }
    }
}

exit
