#!/usr/local/bin/perl

require 5.6.1;
use DBI;

$action  = shift ;
$repos_pwd = shift ;
$interval = shift ;
$OH = $ENV{'ORACLE_HOME'};



if($action !~ /^(start|stop|status)$/)
{
  &printUsage ;
  exit(-1);
}

if(!defined $repos_pwd)
{
  $repos_pwd = &PromptUserPasswd("Enter repository user password : ", 0);
}

&getConnectString ;

$inv = &getStatus ;

if($action eq 'status')
{
  if($inv != 0)
  {
    print "Provisioning Daemon is Up, Interval = $inv\n";
    exit 0;
  }else
  {
    print "Provisioning Daemon is Down\n";
    exit 0;
  }
}elsif($action eq 'start')
{
  if($inv ==  0)
  {
    if(!defined $interval)
    {
      $interval = &PromptUserPasswd("Enter interval [default 3]: ", 1);
      if(!defined $interval || $interval <= 0)
      {
        $interval = 3 ;
      }
    }
    &executeStmt("BEGIN MGMT_PAF_UTL.START_DAEMON($interval); END;");
    $inv = $interval ;
  }
  print "Provisioning Daemon is Up, Interval = $inv\n";
  exit 0;
}elsif($action eq 'stop')
{
  if($inv != 0)
  {
    &executeStmt("BEGIN MGMT_PAF_UTL.STOP_DAEMON; END;");
  }
  print "Provisioning Daemon is Down\n";
  exit 0;
}


sub getStatus
{
  my $ret = &executeQuery('select MGMT_PAF_UTL.DAEMON_STATUS from dual');
  $ret->[0]->[0] ;
}


sub getConnectString
{
  $EM_REPOS_CONNSTRING = undef ;

  $emHome = getEMHome ();

  if ( ! -f "$emHome/sysman/config/emoms.properties" )
  {
    $emHome = $OH;
  }

  if(open(A,"$emHome/sysman/config/emoms.properties"))
  {
   while(<A>)
   {
     if(/oracle\.sysman\.eml\.mntr\.emdRepConnectDescriptor=(.+)/)
     {
       $EM_REPOS_CONNSTRING = $1 ;
       $EM_REPOS_CONNSTRING =~ s/\\//g;
     }
   }
   close(A);
  }else
  {
    die "unable to open $OH/sysman/config/emoms.properties\n";
  }
}
sub PromptUserPasswd($$)
{
   my ($prompt, $echo) = @_;
   my $userinput;
   print $prompt;
   if ($echo eq 0 )
   {
      system "stty -echo"; # Non portable until ReadKey is picked up ...
      $userinput=<STDIN>;
      system "stty echo";  # Non portable until ReadKey is picked up ...
                           # Once ReadKey is picked up use the following.
                           # ReadMode('noecho');
                           # $userinput = ReadLine(0);
                           # ReadMode('normal');
      print "\n";
    }
    else
    {
      $userinput=<STDIN>;
    }
   chomp ($userinput);
   return $userinput;
}

sub executeStmt
{
  my ($query) = @_ ;

  my $lda ; 
  $lda = DBI->connect('dbi:Oracle:', "SYSMAN\@$EM_REPOS_CONNSTRING", "$repos_pwd",     {ora_session_mode => 0, PrintError => 0, RaiseError => 0, AutoCommit => 0})    or (print "Could not connect to SYSMAN/$EM_REPOS_CONNSTRING: $DBI::errstr\n" and exit 50);
  
  $lda->do($query)
      or (print "execute($query): $DBI::errstr\n" and exit 51);
    
  $lda->disconnect or print "disconnect $DBI::errstr\n";
   
  return $result_set ;
   
}

sub executeQuery
{   
  my ($query) = @_ ;
      
  my $lda ; 
  $lda = DBI->connect('dbi:Oracle:', "SYSMAN\@$EM_REPOS_CONNSTRING", "$repos_pwd",     {ora_session_mode => 0, PrintError => 0, RaiseError => 0, AutoCommit => 0})    or (print "Could not connect to SYSMAN/$EM_REPOS_CONNSTRING: $DBI::errstr\n" and exit 50);
  
  my $sql_cur = $lda->prepare($query)
      or (print "prepare($query): $DBI::errstr\n" and exit 51);
    
  $sql_cur->execute()
      or (print "sql_cur->execute(): $DBI::errstr\n" and exit 52);

  my @fetch_row;
  my $result_set = ();

  while (@fetch_row = $sql_cur->fetchrow_array())
  {
    my $array = () ;
    @$array = @fetch_row ;
    push(@$result_set,$array);
  }

  $sql_cur->finish() or print "sql_cur->finish(): $DBI::errstr\n";

  $lda->disconnect or print "disconnect $DBI::errstr\n";

  return $result_set ;

}

sub printUsage
{
  print "Usage : pafctl start|stop|status <sysman password> <interval>\n";
}

sub getEMHome
{
  $cmd = "$OH/bin/emctl getemhome |";
  
  open ( EMCTL_OUTPUT, $cmd ) or die "Unable to get EMHome location $!";

  while (<EMCTL_OUTPUT>)
  {
    if ( $_ =~ /EMHOME/ )
    {
      $emHome = $_;
      chomp($emHome);
      $emHome = substr ( $emHome, 7);
      last;
    }
  }
  close EMCTL_OUTPUT;


  if ( "$emHome" eq "" )
  {
    $emHome = $OH;
  }

  return $emHome
}

