# -*-Perl-*-

# instances allowed: one 

# (single instance modules would be silly to use more than one of
# anyway, so we use package local storage.  This is faster and places
# less artificial load on the machine than doing everything through
# the object hash)

use Tk;
package MGMmodule::diskuse;
use vars qw($xpath $graph $widget $fs $num @data @labels);

sub module_init{
    my$this=shift;
    my$toplevel=$this->{"toplevel"};
    my$xclass=$this->{"xclass"};

    # how many filesystems?
    $this->read_proc;
    unless ($fs>0){
	$toplevel->optionAdd("$xclass*active",'false',21);
    }
    $toplevel->optionAdd("$xclass.order",100,21);
    $this;
}

sub module_instance{
    my$this=shift;
    my$toplevel=$this->{"toplevel"};
    return undef if(defined($xpath));
    $xpath=$this->{"xpath"};
    # modify defaults
    $toplevel->optionAdd("$xpath*scalerefresh",30000,21); # slower
    $this->read_proc;

    undef@labels;
    $num=0;
    for(my$i=0;$i<$fs;$i++){
	my$label=shift @data;
	
	push @labels, ($label);
	my$cap=shift @data;
	my($adj,$mult)=MGM::Graph::scalemod($cap*10);
	$adj=int($adj+.5)/10;

	# modify the label (if needed)

	$toplevel->optionAdd("$xpath.bar.$i.label", "$label $adj$mult",22);
	shift @data;
	$num++;
    }

    $toplevel->optionAdd("$xpath.scalewidadj", 80*$fs,21);  # narrower
    $toplevel->optionAdd("$xpath.bar*litbackground", "#e8d088",21); 

    my($minx,$miny)=&MGM::Graph::calcxysize($this,100,'% used',$fs);

    $toplevel->optionAdd("$xpath.minx",        $minx,21);      
    $toplevel->optionAdd("$xpath.miny",        $miny,21);          
    $this;
}

sub module_run{
    my$this=shift;
    $graph=MGM::Graph->new($this,num=>$fs,
			   prompt=>'% used',fixed=>1,
			   rangesetting=>100,rangecurrent=>100);
    $widget=$graph->{"widget"};
    $this->module_update;
    $widget;
}

sub read_proc{
    my$output=qx{'df' '-k'};
    my@temp=split "\n",$output;
    undef @data;

    $fs=0;
    if($temp[0]=~m/Filesystem/){
	shift @temp;
	while(defined(my$line=shift @temp)){
	    if($line=~m/^\S+\s+(\d+)\s+\d+\s+\d+\s+(\d+)\%\s+(\S+)/){

		# is this a label we want to display?  Filter /proc and AFS
		# for example...

		next if($3=~m/^\/?afs/);
		next if($3=~m/^\/?proc/);
		next if($3=~m/^\/?kern/);

		$fs++;
		push @data, ($3,$1*1024,$2);
	    }
	}
    }
}

sub module_update{
    my$this=shift;
    $this->read_proc;
    my@adj;
    my$i=0;
    while($#data>0){
	return &reconfig if(!defined($labels[$i]));
	return &reconfig if(shift(@data) ne $labels[$i]);
	shift @data;
	push @adj, (shift @data);
	$i++;
    }
    $graph->set(@adj);
    &reconfig if($i!=$num);
}

sub reconfig{
    &main::reinstance() if($widget->optionGet("reconfig","") eq 'true');
}

sub destroy{
    undef $xpath;
}

bless {};

