#!/usr/bin/perl

# $Id: check_mssql.pl,v 1.1 2003/08/29 05:36:49 knitterb Exp $

use DBI;
use Data::Dumper;
use Time::HiRes qw(usleep ualarm gettimeofday tv_interval);
use Getopt::Long;
use strict;

my $server="";
my $uid="";
my $pwd="";

GetOptions ('server|s=s'=>\$server, 'user|u=s'=>\$uid, 'password|p=s'=>\$pwd);
if (check_vars()) {
	exit(-1);
}

my $start_time=[gettimeofday];

my $rc=0;
eval {
	$rc=test();
};
my $duration=tv_interval($start_time);
$duration=($duration*1000);
if (!$rc || $@) {
	print "CRITICAL - $uid\@$server $duration ms $@\n";
	exit(2);
} elsif ($rc) {
	print "OK - $uid\@$server $duration ms\n";
	exit(0);
} 

print "UNKNOWN - rc is $rc\n";
exit(-1);

sub test {
	my $dbh;
	$dbh=DBI->connect("dbi:Sybase:server=$server;".
		"loginTimeout=15;scriptName=nagios",
		$uid, $pwd, {PrintError=>0}) || die "Can't connect $DBI::errstr";
	my @row_ary = $dbh->selectrow_array("select 1")
		|| die "Can't select";
	#print Dumper(\@row_ary);
	if ($row_ary[0] == 1) {
		return(1);
	} else {
		die "Select test did not return 1";
	}
}

sub check_vars {
	if (length($server)<=0) {
		print_usage("Server variable missing");
		return(1);
	}
	if (length($uid)<=0) {
		print_usage("User variable missing");
		return(1);
	}
	if (length($pwd)<=0) {
		print_usage("Password variable missing");
		return(1);
	}
}

sub print_usage {
	my ($msg)=@_;
	if ($msg) {
		print "Error: $msg\n";
	}
	print "\n";
	print "--server -s\t\tServer to connect to\n";
	print "--user -u\t\tUser to connect as\n";
	print "--password -p\t\tPassword for user\n";
	print "\n";
	print "\n";
}

