# -*- perl -*-
#
# $Revision: 1.7 $
package X;

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;

use Socket;

sub print_usage ();
sub print_version ();
sub service_test (%);

sub print_usage () {

    print "
Usage:  Check X service.
Options:
    [--verbose]
    --help
    --version
    --usage
";
    return $ERRORS{'OK'};
}

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

    print "X.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 $X11file = "/tmp/.X11-unix/X0";
    my $fontscheck = "/usr/X11R6/bin/fslsfonts";
    my $desktop = "/etc/sysconfig/desktop";
    my $pscmd = "/bin/ps aux";
    my $mesg = "";

#    if (-x $fontscheck) {
#        `$fontscheck -server unix/:7100` or fail ("Font Server (xfs) not running!");
#        $mesg = "Font Server (xfs) running.";
#    }

    # Does the X socket file exist?  Can you connect to it?
    fail("$X11file is not a socket! $mesg") unless (-S $X11file);
    socket(XSock, PF_UNIX, SOCK_STREAM, 0) or fail("Couldn't initiate socket: $!");
    connect(XSock, sockaddr_un($X11file)) or fail("Couldn't connect to socket: $!");
    close(XSock);

    $mesg = "X11 socket exists and is accepting connections. $mesg";

    my $display;

    if (-f $desktop) {
        # Ok - so x is running - is it running the correct x proc?
        open(DESKTOP, $desktop) or fail("Couldn't open $desktop: $!");
        while(<DESKTOP>) {
            if (/^DISPLAYMANAGER=(.*)$/) {
                $display = $1;
            }
        }
        close DESKTOP;
        ($display) || (fail("DISPLAYMANAGER type is unknown in $desktop! $mesg"));
        $mesg = "Configured as $display. $mesg";
        if ($display eq "GNOME") {
            print "looking for $display process running.\n" if ($options{"verbose"});
            my $procs = `$pscmd`;
            fail("gdm-binary not running! $mesg") unless ($procs =~ /gdm-binary/);
        } elsif ($display eq "XDM") {
            print "looking for $display process running.\n" if ($options{"verbose"});
            my $procs = `$pscmd`;
            fail("xdm not running! $mesg") unless ($procs =~ /xdm/);
        }
    }

    print "OK: $mesg\n";
    exit $ERRORS{OK};
}

sub fail {
    my $text = shift;
    print "CRITICAL: $text\n";
    exit $ERRORS{CRITICAL};
}

