#!/usr/bin/perl 

use Win32;
use Win32::OLE('in');
use English;
use Getopt::Long;
use File::stat;
use constant wbemFlagReturnImmediately => 0x10;
use constant wbemFlagForwardOnly => 0x20;

sub print_help ();
sub print_usage ();

my ($opt_e, $opt_w, $opt_h);
my ($result, $message, $fileage, $filesize, $filestat, $minage, $minsize, $hit, $license_total, $license_used, $license_free, $computer);

my $PROGNAME="check_ctx_licensserver";

#predefined percentage free
$opt_e = 10;
$opt_w = 20; 
$license_total = 0;
$license_used = 0;
$computer = ".";

Getopt::Long::Configure('bundling');
GetOptions(
        "h"   => \$opt_h, "help"        => \$opt_h,
        "e=f" => \$opt_e, "error"       => \$opt_e,
        "w=f" => \$opt_w, "warning"     => \$opt_w
        );

if ($opt_h) {
        print_help();
        exit;
}

$opt_e = shift unless ($opt_e);

if ($opt_e > $opt_w) {
        die('errorlevel must not be higher than warning');
}
 
$objWMIService = Win32::OLE->GetObject("winmgmts:\\\\$computer\\root\\CitrixLicensing") or die "WMI connection failed.\n";

$colItems = $objWMIService->ExecQuery
    ("SELECT * FROM Citrix_GT_License_Pool","WQL",wbemFlagReturnImmediately | wbemFlagForwardOnly);

foreach my $objItem (in $colItems)
{
    $license_used = $license_used + $objItem->{InUseCount};
    $license_total = $license_total + $objItem->{Count};
}

if ($license_total == 0) {
        die('no citrix licenses found. please check if Citrix License WMI Service is running');
}


$license_free = int 100-($license_used/$license_total*100);

# debug
#print "warning level: " . $opt_w . "\n";
#print "error level: " . $opt_e . "\n";
#print "license used: " . $license_used . "\n";
#print "license found: " . $license_total . "\n";
#print "license free: " .  $license_free . "\n\n";


if ( $license_free < $opt_e ) {
        print "Error: you have $license_used licenses in use: $license_free percent\n";
        exit 2; # OK
} elsif  ( ( $license_free > $opt_e ) && ($license_free < $opt_w ) ) {
        print "Warning: you have $license_used licenses in use: $license_free percent\n";
        exit 1; # Warning
} else {
        print "OK: you have $license_used licenses in use: $license_free percent\n";
        exit 0; # OK        
}

sub print_usage () {
        print "Usage:\n";
        print "  $PROGNAME [-e <percentage error>] [-w <percentage warning>]\n";
        print "  $PROGNAME [-h | --help]\n";
}

sub print_help () {
        print "Copyright (c) 2008 Andreas Roth\n\n";
        print_usage();
        print "\n";
        print "  <percentage error> throw errow when less than X percentage of licenses are free\n";
        print "  <percentage warning> throw warning when less than X percentage of licenses are free\n";
        print "\n";
}
