# -*- perl -*-
#
# $Revision: 1.4 $
package ftpusers;

require Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(&print_usage &print_version &service_test);
use lib $main::runtimedir;
use csl_utils qw($TIMEOUT %ERRORS);
use strict;

sub print_usage ();
sub print_version ();
sub service_test (%);

sub print_usage () {

    print "
Usage:  Check number of ftp users.
Options:
    --help
    --version
    --usage
";
    return $ERRORS{'OK'};
}

sub print_version () {
    my $version = '$Revision: 1.4 $';
    $version =~ s/^\$Revision: //;
    $version =~ s/ \$\s*$//;

    print "ftpusers.pm - $version\n";
    return $ERRORS{'OK'};
}

sub service_test (%) {
    my %options = @_;

    if ($options{"verbose"}) {
        foreach my $opt (sort keys(%options)) {
            if ($options{$opt}) {
                print "$opt - $options{$opt}\n";
            }
        }
    }

    my $status = "OK";
    my $FTPCOUNT = "/s/wu-ftpd/bin/ftpcount";
    my $return;

    # get number of users from ftpcount output
    open (USERS, "$FTPCOUNT |") || die "Can't run $FTPCOUNT\n";
    while(my $line = <USERS>) {
        $line =~ /Service class ([\w-]+)\s+-\s+(\d+) users \W*(\w+) maximum/;
        my ($class, $users, $maximum) = ($1, $2, $3);
        ($maximum) || die "Wrong format returned from $FTPCOUNT: $line";
        print "Class: $class, Users: $users, Maximum: $maximum\n" if $options{"verbose"};
        if ($maximum ne "no") {
            if ($users/$maximum > .9) {
                $status = "CRITICAL";
                $return .= "TOO HIGH: ";
            }
        } else {
            $maximum = "unlimited";
        }
        $return .= "$class=$users/$maximum # ";
    }
    close(USERS);

    print "$status: $return\n";
    print "Exit status: $status\n" if $options{"verbose"};

    exit $ERRORS{$status};
}
