#!/usr/bin/perl -w

use strict;
use IO::Handle;
use Socket;
use Sys::Hostname;
use Getopt::Std;

STDERR->autoflush(1);
STDOUT->autoflush(1);

# getopts "H:p:b:a:v:s:t:
# b: base dn; a: atrib; v: value of attrib; s: search string; t: timeout

use vars qw($opt_d $opt_h $opt_H $opt_p $opt_b $opt_a $opt_v $opt_s $opt_t);
getopts("dhH:p:b:a:v:s:t:");

our $Usage = <<EOUSAGE;
Usage:  $0 -H <hostname> [-p <port>] [-t <timeout>] -b <base DN> -a <attribute> -v <value> -s <result string>
EOUSAGE
(print $Usage and exit 3) if $opt_h;

if (!defined($opt_H) or !defined($opt_b) or !defined($opt_a) or !defined($opt_v) or !defined($opt_s)) {
	print $Usage;
	exit 3;
}

our $debug = $opt_d;

our $ThatHost = $opt_H;
our $ThatPort = defined($opt_p) ? $opt_p : 80;
our $TIMEOUT = defined($opt_t) ? $opt_t : 10;

# our $BaseDN = "o=Princeton University,c=US";
# our $Attrib = "uid";
# our $Value = "esm";

our $BaseDN = $opt_b;
our $Attrib = $opt_a;
our $Value = $opt_v;

our $SearchFor = $opt_s;
our @Result;

our $DSML = <<End_Of_Query;
<?xml version='1.0' encoding='UTF-8' ?>
<soap-env:Envelope
   xmlns:xsd='http://www.w3.org/2001/XMLSchema'
   xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
   xmlns:soap-env='http://schemas.xmlsoap.org/soap/envelope/'>
<soap-env:Body xmlns:dsml="urn:oasis:names:tc:DSML:2:0:core">
 <batchRequest>
  <searchRequest dn="$BaseDN"
                 scope="wholeSubtree"
                 derefAliases="neverDerefAliases"
                 sizeLimit="1">
   <filter>
    <equalityMatch name="$Attrib">
     <value>$Value</value>
    </equalityMatch>
   </filter>
   <attributes>
    <attribute name="cn" />
   </attributes>
  </searchRequest>
 </batchRequest>
</soap-env:Body>
</soap-env:Envelope>
End_Of_Query

our $LengthOfDSML = length($DSML);

our $ThisHost = hostname();
our ($AfInet, $SockStream, $SockAddr) = (AF_INET, SOCK_STREAM, 'S n a4 x8');
our ($Name, $Aliases, $Proto) = getprotobyname('tcp');
our ($Type, $Length) = (undef, undef);
our @ThisAddr = ();
our @ThatAddr = ();
($Name, $Aliases, $Type, $Length, @ThisAddr) = gethostbyname($ThisHost);
($Name, $Aliases, $Type, $Length, @ThatAddr) = gethostbyname($ThatHost);
our $This = pack ($SockAddr, $AfInet,         0, $ThisAddr[0]);
our $That = pack ($SockAddr, $AfInet, $ThatPort, $ThatAddr[0]);
if (socket(SOCKET, $AfInet, $SockStream, $Proto)) {
	print STDOUT "TCP socket created\n" if $debug;
} else {
	print "CRITICAL: Cannot connect to $ThatHost:$ThatPort\n";
	exit 2;
}
## if (bind(SOCKET, $This)) {
  ## print STDOUT "Bound to $ThisHost\n";
## } else {
  ## die "Cannot bind to $ThisHost; $!\n";
## }
## our $Error = sprintf 'Timeout connecting to port %u of %s', $ThatPort, $ThatHost;
our $Error = '';
$SIG{ALRM} = sub { print "CRITICAL: Timeout connecting to $ThatHost:$ThatPort\n"; exit 2; };
alarm($TIMEOUT) if $TIMEOUT > 0;
if (connect(SOCKET, $That)) {
	printf STDOUT "Connected to port %u of %s\n", $ThatPort, $ThatHost if $debug;
} else {
	print "CRITICAL: Cannot connect to $ThatHost:$ThatPort\n";
	exit 2;
}

alarm(0);

$SIG{ALRM} = 'DEFAULT';
SOCKET->autoflush(1);

our $HTTPandDSML = <<EODSML;
POST / HTTP/1.1
Host: $ThisHost
Content-Type: text/xml; charset="utf-8"
Content-Length: $LengthOfDSML
SOAPAction: dsml://$ThatHost/

$DSML
EODSML

select SOCKET; $|=1; select STDOUT;
$SIG{ALRM} = sub { print "CRITICAL: Timeout receiving response from $ThatHost:$ThatPort\n"; exit 2; };
alarm($TIMEOUT) if $TIMEOUT > 0;
print STDOUT $HTTPandDSML if $debug;
print SOCKET $HTTPandDSML;

while (<SOCKET>) {
	print STDOUT if $debug;
	chop;
	push @Result, $_;
	next unless m|</soap-env:Envelope>|is;
	$Error = '';
	last;
}

alarm(0);
$SIG{ALRM} = 'DEFAULT';
close SOCKET;

if ($Result[0] !~ /HTTP\/.*200 OK/) {
	print "CRITICAL: DSML query returned $Result[0]\n";
	exit 2;
}

my $s;

foreach $s (@Result) {
	if ($s =~ /$SearchFor/) {
		print "OK: lookup of $Attrib=$Value succeeded\n";
		exit 0;
	}
}

print "CRITICAL: lookup of $Attrib=$Value failed\n";
exit 2;

