#!/usr/bin/perl
# embedded perl von nagios deaktivieren
# http://nagios.sourceforge.net/docs/3_0/embeddedperl.html
# nagios: -epn

use strict;
use utf8;
use warnings;

use Data::Dump qw(pp);          # depends: libdata-dump-perl
use noris::IO::AutoEncoding;    # depends: libnoris-io-autoencoding-perl

use WWW::Mechanize;
use HTTP::Cookies;

use Getopt::Long;

$ENV{PERL_LWP_SSL_VERIFY_HOSTNAME} = 0;


GetOptions(
    'host=s' => \my $Host,

    'username=s' => \my $Username,
    'password=s' => \my $Password,

    'warning=i'  => \my $Warning,
    'critical=i' => \my $Critical,
 
		'absolute!'  => \(my $Absolute = 0 ), 

    'debug!'     => \( my $Debug = 0 ),
		'help|?'     => \our $Help,
) or exit 1;

exec perldoc => -F => $0 or die "exec('perldoc -F $0'): $!\n" if $Help;

nagexit( "UNKNOWN: Parameter --host is needed",       3, 0 ) unless $Host;
nagexit( "UNKNOWN: Parameter --username is needed",   3, 0 ) unless $Username;
nagexit( "UNKNOWN: Parameter --password is needed",   3, 0 ) unless $Password;
nagexit( "UNKNOWN: Parameter --warning is needed",    3, 0 ) unless $Warning;
nagexit( "UNKNOWN: Parameter --critical is needed",   3, 0 ) unless $Critical;
nagexit( "UNKNOWN: Parameter --critical < --warning", 3, 0 ) if $Critical < $Warning;
nagexit( "UNKNOWN: Parameter --critical or --warning must be between 0 and 100", 3, 0 ) if ( $Critical < 0 or $Critical > 100 or $Warning < 0 or $Warning > 100 );

my $mech = WWW::Mechanize->new();
$mech->cookie_jar( HTTP::Cookies->new() );
$mech->get( 'https://' . $Host . '/admin/' );
nagexit( "Error Loading 'https://$Host/admin/' Login Page", 3, 0 ) unless $mech->success();

# Login into Admin Site
$mech->submit_form(
    with_fields => {
        'username' => $Username,
        'password' => $Password,
    },
);
nagexit( 'UNKNOWN: Error submitting Login Form', 3, 0 ) unless $mech->success();

my $output_page = $mech->content();

# If another user is logged in (confirmation is needed)
if ( $output_page =~ m/frmConfirmation/ ) {
    $mech->submit_form( form_name => 'frmConfirmation', button => 'btnContinue' );
    nagexit( 'UNKNOWN: Error submitting confirmation Page', 3, 0 ) unless $mech->success();
    $output_page = $mech->content();
}

print $output_page if $Debug;

# Parse HTML and find Number of users logged in
open( my $DATA, '<', \$output_page ) or do {
    $mech->get( 'https://' . $Host . '/dana-admin/misc/admin.cgi' );
    nagexit( 'UNKNOWN: Error opening DATA FH', 3, 0 );
};


my $mfound=0; my $found = 0;
my $maxusers=0; my $users=0;
while (<$DATA>) {
    if ( m/Max Licensed Users:/ ) {
      $mfound = 1;
    }
    if ( m/Signed-In Users\s+\[Device\]:/ ) {
      $found = 1;
    }
    if ( m!<td><span class="cssSmallWhite">(\d+)</span></td>! ) {
      if ( $mfound == 1 ) {
        $maxusers = $1;
        $mfound = 0;
      }
      if ( $found == 1 ) {
        $users = $1;
        $found = 0;
        last;
      }
   }
}

close $DATA or nagexit( 'UNKNOWN: Error closing DATA FH', 3, 1 );
print "Logged in Users: '$users'\n" if $Debug;
print "Max Users: $maxusers\n" if $Debug;

# Logout from Page
$mech->get( 'https://' . $Host . '/dana-na/auth/logout.cgi' );
nagexit( 'UNKNOWN: Error Logging out', 3, 0 ) unless $mech->success();

if ( $Absolute ) {
	print "W: $Warning - C: $Critical - M: $maxusers\n" if $Debug;

	nagexit( "CRITICAL: $users of $maxusers already logged in", 2, 0 ) if $users > $Critical;
	nagexit( "WARNING: $users of $maxusers already logged in",   1, 0 ) if $users > $Warning;
	nagexit( "OK: $users User(s) of $maxusers logged in", 0, 0 );

} else {

	my $warnlimit = $Warning/100;
	my $critlimit = $Critical/100;
	my $usage = $users/$maxusers;
 
	print "W: $warnlimit - C: $critlimit - P: $usage\n" if $Debug;

	nagexit( "CRITICAL: $users of $maxusers already logged in", 2, 0 ) if $usage > $critlimit;
	nagexit( "WARNING: $users of $maxusers already logged in",   1, 0 ) if $usage > $warnlimit;
	nagexit( "OK: $users User(s) of $maxusers logged in", 0, 0 );
}

# Helper Subs
sub nagexit {
    my ( $msg, $code, $logout ) = @_;
    print "$msg\n";
    $mech->get( 'https://' . $Host . '/dana-na/auth/logout.cgi' ) if $logout;
    exit $code;
}

__END__

=encoding utf8

=head1 NAME

check_juniper_sslvpn_users - Check Number of Users Logged in

=head1 SYNOPSE

    check_juniper_sslvpn_users -host 'juniper.example.com' \
         -username ADMIN \
         -password **** \
         -warning  10 (in %)\
         -critical 20 (in %)
				 -absolute

=head1 BESCHREIBUNG

Liest die maximal erlaubten User aus, sowie die momentan eingeloggten.
 SNMP liefert hier nicht die gewünschten Daten.
 (s. #15547848)

=head1 RÜCKGABEWERT

0 (OK)
1 (warning)
2 (critical)
3 (unknown)

=head1 OPTIONEN

=over 4

=item -host HOSTNAME

Der Host der überwacht werden soll.

=item -username USERNAME

=item -password ********

Die Logindaten fürs Admin-FE

=item -warn INT

=item -crit INT

Ab welchem Schwellenwert ist es ein Warning und wann ein Critical

=item -absolute

(optional)
 
Es können absolute -w(arning), -c(ritical) Werte angegeben werden, keine Prozentzahlen

=item -help

=item -?

um (nur) diese Dokumentation anzeigen zu lassen

=back

=head1 AUTOREN

 Stelios Gikas <entwicklung@ticket.noris.net>
 Stelios Gikas <11018197@ticket.noris.net>

=cut
