#!/usr/bin/perl -w

use strict;
use DBI;
use Time::Format qw(%time);

my $debug = '0';

############## Database Configuration 
# $ENV{ORACLE_HOME} Path to oracle installation
# $dbuser oracle account used to connect to oracle 
# $dbpass oracle password for account 
# @db = qw( instance1 ...) tnsname of database to check

$ENV{ORACLE_HOME} = '/opt/oracle/product/8.1.7';
my $dbuser = 'db_username';
my $dbpass = 'db_password';
my @db = qw( instance1 );

foreach my $db (@db)  {
       my $result = check_db($db);
       if($result) {
       	foreach (@$result) {
         	if ( @$_[0] =~ /^\bOPEN\b$/ ) {
            	debug($db,'OK');
            } else {
			debug($db,'DOWN');
			logit("ORACLE $db down, but monitor should be true");
			exit 0;
            }
         }
       } else {
		logit("ORACLE  $db down, but should be true");
		exit 0;
       } 
}

logit('Starting JAVA Application');
chdir("/opt/OLY/bin") || die "Cannot chdir: ($!)\n";
system('/opt/sbin/runas app app 002 ./java_app.sh start');
sleep 60;

sub check_db {
	my ($db) = shift;
	my $dbh = DBI->connect("dbi:Oracle:$db", $dbuser, $dbpass, { 
		RaiseError => 0,
            AutoCommit => 1,
            PrintError => 0 });  

	unless ( $dbh ) {
      	#warn "Could not connect to $db: $DBI::errstr\n" ;
            return 0;
	}

	my $sth = $dbh->prepare("select status from v\$instance");
	$sth->execute;
	my $row = $sth->fetchall_arrayref;
	$sth->finish;
	$dbh->disconnect;
	return $row;
}

sub debug {
	my ($foo,$bar) = @_;
	printf("%-22s %-22s %-5s\n",$time{'dd/mm/yy hh:mm:ss.mmm'},$foo,$bar) if ($debug);
}

sub logit {
	my $message = shift;
	system("/usr/bin/logger -p daemon.notice -t Cluster.oly-java $message");
}
