#!/usr/local/bin/perl -w

# (c)2004 John Koyle, RFP Depot, LLC.
# This is free software use it however you would like.

use strict;
use DBI;
use Getopt::Long 2.16;
use lib "/usr/local/nagios/libexec";
use utils qw(%ERRORS);


#*******************************************************************************
# Set user configureable options here.
#
# Global Oracle info set here rather than command line to avoid output in ps -ef
# Make sure this script is mode 700 and owner of the nrpe user
#
#*******************************************************************************
my $orasid = "";
my $orauser = "";
my $orapwd = "";


if (!$ENV{ORACLE_HOME}) {
        $ENV{ORACLE_HOME} = '/u01/app/oracle/product/9.2';
}

#*******************************************************************************
my $state = $ERRORS{'UNKNOWN'};
my $answer = undef;

my ($MAJOR_VERSION, $MINOR_VERSION) = q$Revision: 1134 $ =~ /(\d+)\.(\d+)/;
my $VERSION = sprintf("%d.%02d", $MAJOR_VERSION - 1, $MINOR_VERSION);

my $opt_debug;                  # -d|--debug
my $opt_help;                   # -h|--help
my $opt_version;		# -V|--version
my $opt_warn_space; 	        # -w|--warn-space
my $opt_crit_space; 	        # -c|--crit-space



my $help = <<MARK;      # help statement

check_oracle_tbs v$VERSION

Checks the tablespaces in an Oracle database for available free space.
Usage: check_oracle_tbs [-w <warn>] [-c <crit>]

  -d, --debug              Output debug to screen.
  -h, --help               Displays this help and exits.
  -w, --warn-space=...     Warning threshold % free (default 15)
  -c, --crit-space=...     Critical threshold % free (default 10)
  -V, --version            Output version information and exit.

MARK

## We want exact matches to the switches

Getopt::Long::config('no_auto_abbrev', 'no_ignore_case');


my $rc = GetOptions(
                "debug|d"               => \$opt_debug,
                "help|h"                => \$opt_help,
                "w|warn-space=s"        => \$opt_warn_space,
                "c|crit-space=s"        => \$opt_crit_space,
                "V|version"             => \$opt_version,
                   );


#***********************************************************************
# Process command-line switches
#***********************************************************************

if (! $rc || defined $opt_help)
{
    print STDERR $help;
    exit (defined $opt_help ? 0 : 1);
}

if (defined $opt_version)
{
    print STDERR "check_oracle_tbs v$VERSION\n";
    exit 0;
}

if (! defined $opt_warn_space)
{
    if(defined $opt_debug) {
        print STDOUT "Warn space not defined, using 80%\n\n";
    }
    $opt_warn_space = 15;
}

if (! defined $opt_crit_space)
{
    if(defined $opt_debug) {
        print STDOUT "Crit space not defined, using 90%\n\n";
    }
    $opt_crit_space = 10;
}

my $array_ref = executeSQL();

# Don't match certain tablespaces.
foreach my $row (@$array_ref) {
    my ( $tbs_name, $free_mb, $tot_mb, $free_pct) = @$row;
    if ($opt_debug) { print STDOUT "Output: $tbs_name\t$tot_mb\t$free_mb\t$free_pct\n\n"; }
    if ($free_pct < $opt_crit_space && $tbs_name !~ /RBS/ && $tbs_name !~ /PERFSTAT/ && $tbs_name !~ /UNDOTBS/) {
        $state = $ERRORS{'CRITICAL'};
        $answer .= "Critical: $tbs_name = $free_pct\% ";
        last;
    }
    if ($free_pct < $opt_warn_space && $tbs_name !~ /RBS/ && $tbs_name !~ /PERFSTAT/ && $tbs_name !~ /UNDOTBS/) {
        $state = $ERRORS{'WARNING'};
        $answer .= "Warning: $tbs_name = $free_pct\% ";
    }
}

if ($state != $ERRORS{'CRITICAL'} && $state != $ERRORS{'WARNING'}) {
    $state = $ERRORS{'OK'};
    $answer = "All Tablespaces OK";
}

if ($opt_debug && $state != $ERRORS{'OK'}) { print STDOUT "The following tablespaces are in question: $answer\n\n"; }

foreach my $key (keys %ERRORS) {
        if ($state==$ERRORS{$key}) {
                print ("$key: $answer");
                last;
        }
}
exit $state;

#------------------SUBS-------------------------------------------------------
sub executeSQL
{
    my ($dbh, $sth, $results);

    $dbh = openOracle();

    eval {
      $dbh->{RaiseError} = 1;
      $sth = $dbh->prepare(q{
         select ts.tablespace_name,
                trunc(sum(ts.free_b)/1024/1024) free,
                trunc(sum(ts.max_b)/1024/1024)  total,
                trunc( sum(ts.free_b)/sum(ts.max_b)*1000) / 10 as pct_free
          from
                (select a.file_id,
                        a.tablespace_name,
                        decode(a.autoextensible,'YES',a.maxsize-a.bytes+b.free,'NO',b.free) free_b,
                        a.maxsize max_b
                   from (select file_id,
                                tablespace_name,
                                autoextensible,
                                bytes,
                                decode(autoextensible,'YES',maxbytes,bytes) maxsize
                           from dba_data_files) a,
                        (select file_id,
                                tablespace_name,
                                sum(bytes) free
                           from dba_free_space
                       group by file_id, tablespace_name) b
                  where a.file_id=b.file_id(+)) ts
       group by tablespace_name
         });

      $sth->execute();
      $results = $sth->fetchall_arrayref();
      $sth->finish;
      $dbh->{RaiseError} = 0;
    };

    if ($@) {
      closeOracle($dbh);
      if($opt_debug) { print STDOUT "DB Failed Query: $@\n"; }
      CleanupAndExit($ERRORS{'UNKNOWN'});
    }

    closeOracle($dbh);

    return $results;
}

#------ Open the connection to the database and return the handle
sub openOracle
{
   my ($dbh);

   $dbh = DBI->connect("$orasid", "$orauser", "$orapwd", "Oracle");

   if (!$dbh) {
      if ($opt_debug) { print "ERROR: Could not connect to Oracle!\n\n"; }
      CleanupAndExit($ERRORS{'UNKNOWN'});
   }
   if ($opt_debug) { print "Connected to Oracle SID $orasid\n\n"; }
   return $dbh;
}

#------- Close the database connection
sub closeOracle()
{
   my ($dbh) = @_;

   $dbh->disconnect;
}

#------ Exit with the current return code
sub CleanupAndExit
{
        my ($rc) = @_;

        exit($rc);
}

