# -*- perl -*-
#
# $Revision: 1.2 $
package xvfb;

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

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

    print "xvfb.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 $host = $options{"opt_H"};

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

    my $xdpyinfo = "/usr/bin/xdpyinfo -display $host:3";

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

    open CMD, "$xdpyinfo 2>&1 |";

    my ($version_number, $XOrg_version);

    LOOP: while ( <CMD> ) {
        if ( /unable to open display/ ) {
            print "CRITICAL: xvfb not up.  \'$xdpyinfo\' unable to open display.\n";
            exit $ERRORS{"CRITICAL"};
        }

        if ( /^version number:\s+([\d\.]+)$/ ) {
            $version_number = $1;
        } elsif ( /^X.Org version:\s([\d\.]+)$/ ) {
            $XOrg_version = $1;
            last LOOP;
        }
    }
    close CMD;

    my $status = "OK";

    ($version_number) || ($version_number = "UNDEFINED");
    ($XOrg_version) || ($XOrg_version = "UNDEFINED");

    $status = "WARNING" if (($version_number eq "UNDEFINED") || ($XOrg_version eq "UNDEFINED"));
    
    print "$status: xdpyinfo returned version number=$version_number and X.Org version=$XOrg_version\n";
    print "Exit status: $status\n" if $options{"verbose"};

    exit $ERRORS{$status};
}

