# -*-Perl-*-

# this module is a hack; it isn't a widget builder.  It sits in the background
# and reads /proc/stat for other modules to reduce opens/closes.

# It defines an init method that installs the /proc/stat listener,
# then marks itself 'inactive' so that mgm doesn't try to call _run,
# _update or allocate space.  The last part of the hack is the name
# beginning with 00 so that it loads before the other modules that
# depend on it


package MGMmodule::helperST;
use vars qw(%proc %net $lastmod $active);
use IO::Seekable;

sub module_init{
    my$this=shift;
    my$xclass=$this->{"xclass"};
    my$toplevel=$this->{"toplevel"};
    my$widget=$this->{"widget"};
    
    $toplevel->optionAdd("$xclass.scalerefresh",500,21); # keep up with cpustat
    my$refresh=$widget->optionGet("scalerefresh","");
    
    $lastmod=0;
    $active=0;
    if(open(PROC,"/proc/stat")){
	if(open(NET,"/proc/net/dev")){
	    $active=1;
	    $this->module_update;
	    $toplevel->repeat($refresh,\&module_update)if(defined(%proc));
#	    &MGM::schedule::perm_schedule($this,$refresh);
	}
    }
    $toplevel->optionAdd("$xclass.active",0,21);
    $this;
}

sub module_instance{
    shift;
}

sub module_update{
    my$data;
    my$netd;
    sysseek PROC, 0, SEEK_SET;
    sysseek NET, 0, SEEK_SET;
    sysread NET,$netd,1024;
    sysread PROC,$data,4096;

    map{
	my$pos=rindex $_, ":";
	if($pos>0){
	    my$key=substr $_,0,$pos;
	    $key=~s/^\s*(\S+)/$1/;
	    $net{$key}=substr $_, $pos+1;
	}
    } split "\n", $netd;

    map{
	m/^(\S+)\s+(.*)/;
	$proc{$1}=$2;
    } split "\n", $data;

    # what a great hack
    $proc{"cpu"}=~m/(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/;
    $lastmod=$1+$2+$3+$4; # 100ths of a second
}

bless {};


