package Requester::df;

use strict;

@Requester::df::ISA = qw(Requester::Requester);

my $requester = new Requester::df;
my $guessed_df = "";
my $fsindex = {};

sub new
{
    my ($this, $args ) = @_;
    my  $class = ref($this) || $this;
    my  $self = {};

    bless($self, $class);
    $self->register( "df" );
    $self->{"index"} = {};
    $self->{"deviceindex"} = {};
    return $self;
}


sub guess_df {
    return( $guessed_df ) if( $guessed_df );
    my $maybecomm;
    foreach my $df (  "df -k -B", "bdf", "df -T", "df -k", "df -k -I", "df" ) {
        open( DF, "$df 2>/dev/null|" );
	my $line1 = <DF>;
	my $line2 = <DF>;
	close DF;
	next if( $? || ! $line1 );
	$maybecomm = $df;
	if( $line1 =~ /ilesystem/ ) {
	    $guessed_df = $df;
	    last;
	}
    }
    ($guessed_df = $maybecomm) unless( $guessed_df );
    ($guessed_df = "true") unless( $guessed_df );
    return $guessed_df;
}


sub request {
    my( $self, $env, $domain, $variables ) = @_;

    my $df = $env->expand_value( "dfcommand" );
    $df = $self->{"dfcommand"} unless( $df );
    $df = guess_df() unless( $df );
    $self->{"dfcommand"} = $df;
    Requester::Requester::request( @_ );
}



sub getinfo {
    my( $self, $gets, $indexes ) = @_;

    my @indexes = $indexes ? @$indexes : ();
    my $command = $self->{"dfcommand"};
    if( @indexes ) {
        foreach my $index (@indexes) {
	    if( defined $self->{"index"}->{$index} ) {
	        $command .= " ".($self->{"index"}->{$index});
	    }
	}
    }
    print "  df requester running $command\n" if( $BigSister::common::dl > 6 );
    open( DF, "$command|" );
    my $started = 0;
    my %info = ();
    while( <DF> ) {
        next if( /^File/i && ! $started );
	chomp;
	my @words = split( /[\s\t]+/ );
	if( $#words < 1 ) {
	    # continuation
	    chomp( $_ = <DF> );
	    s/^[\s\t]+//;
	    push( @words, split( /[\s\t]+/ ) );
	}
	next if( $#words < 5 );
	$started = 1;
	my( $device, $fstype, $size, $used, $available, $usage, @mp );
	if( $words[1] =~ /^\d+$/ ) {
	    ( $device, $size, $used, $available, $usage, @mp ) = @words;
	}
	else {
	    ( $device, $fstype, $size, $used, $available, $usage, @mp ) = @words;
	}
	my $idx;
	unless( defined $self->{"deviceindex"}->{$device} ) {
	    my @indexes = keys %{$self->{"index"}};
	    $idx = $#indexes + 1;
	    $self->{"deviceindex"}->{$device} = $idx;
	    $self->{"index"}->{$idx} = join( " ", @mp );
	}
	else {
	    $idx = $self->{"deviceindex"}->{$device};
	}
	$info{$idx} = {
	    "hrStorageDevice" => $device,
	    "hrStorageFSType" => $fstype,
	    "hrStorageSize" => $size,
	    "hrStorageUsed" => $used,
	    "hrStorageAvailable" => $available,
	    "hrStorageUsage" => $usage,
	    "hrStorageDescr" => join( " ", @mp ),
	    "hrStorageAllocationUnits" => 1024,
	    "hrStorageIndex" => $idx,
	    "hrStorageType" => "1.3.6.1.2.1.25.2.1.4"
	};
    }
    close DF;
    return \%info;
}


1;

