#!/usr/bin/perl

#---------------------------------------------------------------
# See ../Config/radius for documentation.
#
# Kevin O'Donnell
# Vancouver, Canada
# kevin_odonnell@telus.net
#
#---------------------------------------------------------------

package Monitor::radius;

require 5.002;
require Exporter;

use strict;
use Authen::Radius;

@Monitor::radius::ISA = qw(Exporter Monitor::Monitor);

sub new
{
    my ($this) = @_;
    my  $class = ref($this) || $this;
    my  $self = {};
	$self->{htable} = [];

    bless($self, $class);
    return($self);
}

sub add {
	my $self = shift;
	my $host = shift;	# radius server
	my $secret = shift;	# shared secret
	my $port = shift;	# radius port
	my $user = shift;	# username to check
	my $pass = shift;	# password to check
	my $item = shift;	# item to report (host.test)
	my $time = shift;	# number of seconds to wait before reporting timeout

	# set port to default radius port unless specified
	$port = $port ? $port : 1645;

	# complain complain complain
	if (! $host) { print "radius_add(): ENOHOST; no hostname specified\n"; exit(0); }
	if (! $user) { print "radius_add(): ENOUSER; no username specified\n"; exit(0); }
	if (! $pass) { print "radius_add(): ENOPASS; no passname specified\n"; exit(0); }

	print "radius::add( $host, $secret, $port, $user, $pass, $item, $time)\n" if ($BigSister::common::dl > 3);

	# create new radius object for this host
	my $radius = Authen::Radius->new(
		Host => "$host:$port",
		Secret => $secret,
		TimeOut => $time
		);

	# store the information for this test in @htable
	push(@{ $self->{htable} },[$radius,$user,$pass,$item]);

	return(1);
}

sub check {
 	my $self = shift;
	my $check;

	# step through each host and perform a user authentication request
	foreach $check (@{ $self->{htable} }) {

		my ($radius,$user,$pass,$item) = @{ $check }; 
		print "radius::check( $item, $user, $pass) -> " if( $BigSister::common::dl>3 );

		# query the radius server
		my $result = $radius->check_pwd($user,$pass);

		if (! $result) {
			# an error occured
			my $err = $radius->get_error();
			my $errstr = $radius->strerror();
			if ($err eq 'ENONE') {
				$err = "AUTHFAILED";
				$errstr = "received response from radius but authentication failed";
			}
			print "$err: $errstr\n" if( $BigSister::common::dl > 3 );
			# report RED
 			$self->report( $item, $BigSister::common::status_codes{"red"}, "$err: $errstr" );
		} else {
			# report GREEN
			print "ok\n" if ( $BigSister::common::dl > 3 );
 			$self->report( $item, $BigSister::common::status_codes{"green"}, "OK");
		}
	}
}

sub late_check {
	# NOOP #
	return(1);
}

1;
