# -*- perl -*-
#
# $Revision: 1.1 $
package flexlm;

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 flexlm service.
Options:
    -H <hostname> -P <portnumber> [--verbose]
    --help
    --version
    --usage
";
    return $ERRORS{'OK'};
}

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

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

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

    my $lmstat = "/s/lmgrd/bin/lmstat";

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

    my $host = $options{"opt_H"};

    if ((!$host) || ($host eq "")) {
        print "\nHost name not specified.\n";
        &print_usage();
        return $ERRORS{'OK'};
    }

    my $port = $options{"opt_P"};

    if ((!$port) || ($port eq "")) {
        print "\nPort number not specified.\n";
        &print_usage();
        return $ERRORS{'OK'};
    }


    ($host) =~ s/([^\.]*).*/$1/;
    my @ports = split(",", $port);

    my $licfile;
    my ($file, $status, $name, $version);
    my $progstatus = "OK";
    my @print;

    foreach my $port (@ports) {

        $licfile = "$port\@$host";

        print "$licfile\n" if $options{"verbose"};

        $file = "license server not running";
        $status = "CRITICAL";
        $name = "unknown";
        $version = "???";

        open CMD,"$lmstat -c $licfile |";
        while ( <CMD> ) {
            if ( /License file/ ) {
                ($file) = /^[^:]*: ([^:]*):.*/;
            } elsif ( /$host.*license server UP/ ) {
                $status = "OK";
            } elsif ( / *([^:]*): UP (.*)/ ) {
                $name = $1;
                $version = $2;
            }
        }

        print "$status - $port - $file\n" if $options{"verbose"};
        push @print, "$status: $port/$name-$version";

        if ($ERRORS{$status}) {
            $progstatus = $status;
        }
    }

    my $printme = join(" , ", @print);

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

    exit $ERRORS{$progstatus};
}
