package Monitor::etherport;

# Author:   Thomas Aeby
#
# Author:   mrwizard@psu.edu (Joseph Gooch)
#

require 5.002;
require Exporter;

use strict;
use vars qw(@ISA @EXPORT $VERSION
            $def_timeout $def_proto $max_datasize);

use Carp;

@ISA = qw(Exporter Monitor::Monitor);
$VERSION = 2.02;

sub new
{
    my ($this,
	$host,
	$community,
	$frequency,
	$snmp
        ) = @_;
    my  $class = ref($this) || $this;
    my  $self = {};
    my %ports = {};
    my ($cnt,               # Count through data bytes
        $min_datasize       # Minimum data bytes required
        );

    bless($self, $class);

    croak("Must give switch host") unless $host;
    ($community="public") unless $community;

    $self->{"snmp"} = $snmp = Monitor::snmp->new( $host, $community );

    my @sub = $snmp->walk( "ifDescr" );
    my $i;
    foreach $i (@sub) {
	#print "   walked, got $i\n" if ($BigSister::common::dl);
	my $pos = index( $i, ":" );
	next if( $pos<0 );
	my $soid = substr( $i, 0, $pos );
	my $val = uc(substr( $i, $pos+1 ));
	$val =~ s/^\"//;
	$val =~ s/\".*//;
	$ports{$val}="".$soid;
	$ports{"".$soid}=$val;
	print "$host Port: $val  =  Num: $soid\n" if ($BigSister::common::dl);
    }

    $snmp->add_walk ( "ifOperStatus" );

    $self->{"switch"} = $host;
    $self->{"community"} = $community;

    $self->{"ptable"} = \%ports;
    my( @bla)  = ();
    $self->{"htable"} = \@bla;

    return($self);
}


sub add_check {
    my( $self , $host, $item, $port ) = @_;
    my( $htable ) = $self->{"htable"};
    my( $ptable ) = $self->{"ptable"};

    ($item = "$host\.port") unless ($item);
    ($port = uc($port)) if ($port);
    print "add_check $self->{switch} using $item, $port " if ($BigSister::common::dl);
    ($port = 0) unless($port);
    unless ($port =~ /^[0-9]*$/) {
	($port = $$ptable{$port}) if (defined $$ptable{$port});
    }
    ($port = 0) unless($port);
    print "port resolved $port \n" if ($BigSister::common::dl);

    push( @$htable, [ $host, $item, $port ] ); 
}

sub check {
    my ($self) = @_;
}

sub late_check
{
    my ($self) = @_;
    my ( $row );
    my( $htable ) = $self->{"htable"};
    my( $ptable ) = $self->{"ptable"};
    my (%value) = ( '1' => 'up(1)',
		    '2' => 'down(2)' );   

    foreach $row (@$htable) {
	my ( $vars ) = $uxmon::monitor_variables{$self->{"switch"}};
	my ( $color, $probs, $text );

	my $oper = $vars->{"snmp.ifOperStatus.$$row[2]"};

	$probs="";
	$text = "Switch: $self->{switch}  Port: $$ptable{$$row[2]}  State: $value{$oper}";
	if ($oper == 1) {
	    $color=$BigSister::common::status_codes{"green"};
	} else {
	    $color=$BigSister::common::status_codes{"red"};
	    $probs.="&red Connection down";
	}
	print "$$row[1] $color $probs\n\n$text\n" if ($BigSister::common::dl);
	$self->report($$row[1], $color, "$probs\n\n$text");
    }
}

1;
