#!/usr/bin/perl
#####################################################################
#
# check_mysql_number_tables.pl version 1.01
# copyright (c) 2005 Brian
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# contact the author directly for more information at:
# spatuality at yahoo dot ca
#
#####################################################################
#
# Check how many tables are in a MySQL database.
# This plugin requires that mysql is installed on the system.
#
# If no parameters are givin, a usage statement is output.
#
# Exit 0 on success, providing some informational output
# Exit 2 on failure.
#

require 5.004;

sub usage;

my $TIMEOUT = 15;
my $MYSQL = "mysql";

my %ERRORS = ('UNKNOWN' , '-1',
              'OK' , '0',
              'WARNING', '1',
              'CRITICAL', '2');

my $host = shift || &usage(%ERRORS);
my $user = shift || &usage(%ERRORS);
my $pass = shift || "";
my $TABLE = shift || "mysql";
my $warn = shift || 20;
my $crit = shift || 30;

my $state = "OK";
my $count = 0;
my $status = "";

# Just in case of problems, let's not hang Nagios
$SIG{'ALRM'} = sub {
     print ("ERROR: No response from MySQL server (alarm)\n");
     exit $ERRORS{"UNKNOWN"};
};
alarm($TIMEOUT);

open (OUTPUT, "$MYSQL -h $host -u $user --password=\"$pass\" $TABLE -e 'show tables;' | wc -l 2>&1 |");

while (<OUTPUT>) {
  if (/failed/) { $state="CRITICAL"; s/.*://; last; }
  chomp;
  $count = $_ - 1;
}

if ($count >= $warn) { $state = "WARNING"; }
if ($count >= $crit) { $state = "CRITICAL"; }

$status = "Tables $state - $count Tables\n";

print $status;
exit $ERRORS{$state};

sub usage {
   print "Required arguments not given!\n\n";
   print "MySQL table count plugin for Nagios, V1.01\n";
   print "Copyright (c) 2005 Brian Zammit \n\n";
   print "Usage: check_mysql.pl <host> <user> [<pass> <table> [<warn> [<crit>]]]\n\n";
   print "       <pass> = password to use for <user> at <host>\n";
   print "       <table> = table to use\n";
   print "       <warn> = number of threads to warn us about\n";
   print "       <crit> = number of threads to scream at us about\n";
   exit $ERRORS{"UNKNOWN"};
}
