#! /usr/bin/perl -w

# flexlm check module

# Version: $Revision: 0.4 $
# Author: Matt Selsky <selsky@columbia.edu>
# Date: $Date: 2003/01/29 01:12:38 $

# Copyright (c) 2002 - 2003
# The Trustees of Columbia University in the City of New York
# Academic Information Systems
# 
# License restrictions apply, see doc/license.html for details.

use strict;
use FindBin;
use lib "$FindBin::Bin/../common";
use Survivor::Check;

my %argfmt = ("license" => "file");

my $sc = new Survivor::Check();

$sc->GetOpt(\%argfmt, \&FlexlmValidate);

my $r = $sc->Exec( \&FlexlmCheck);

exit($r);

sub FlexlmValidate {
    my $self = shift;

    defined $self->Which('lmstat') or
	return(MODEXEC_MISCONFIG, 0, 'lmstat executable not found');

    return(MODEXEC_OK, 0, "Flexlm OK");
}

sub FlexlmCheck {
    my $self = shift;
    my $host = shift;

    my $license = $self->Arg('license');

    my $LMSTAT = $self->Which('lmstat');

    unless(defined $LMSTAT) {
	return(MODEXEC_MISCONFIG, 0, 'lmstat executable not found');
    }

    # XXX what if $host == 'localhost'?
    my $fullname = (gethostbyname($host))[0];

    my($status,$err);

    open(LMSTAT, "$LMSTAT -a -c $license 2>&1|");

    my $line;
    while( defined($line = <LMSTAT>) ) {
        chomp $line;
        if( $line =~ /^$fullname:\s/ ) {
	    if( $line =~ / UP / ) {
		$status = 1;
	    } else {
		$err = $line;
		$err =~ s/.*: //;
		$status = 0;
	    }
            last;
	}
    }

    close(LMSTAT);

    if(defined $status) {
	if($status == 1) {
	    return(MODEXEC_OK, 1, 'License server up');
	} else {
	    return(MODEXEC_PROBLEM, 0, $err);
	}
    } else {
	return(MODEXEC_PROBLEM, 0, 'No response from license server');
    }
}
