#!/usr/local/bin/perl
# 
# $Header: emd_uploadstats.pl 15-sep-2004.13:15:57 kduvvuri Exp $
#
# emd_uploadstats.pl
# 
# Copyright (c) 2002, 2004, Oracle. All rights reserved.  
#
#    NAME
#      emd_uploadstats.pl
#
#    DESCRIPTION
#  
#
#    NOTES
#  
#
#    MODIFIED   (MM/DD/YY)
#    kduvvuri    09/15/04 - add tracing. 
#    kduvvuri    06/22/04 - performance fix - bug 3672890. 
#                           call emdctl directly.
#    vnukal      12/03/03 - expecting 0 succ return code 
#    vnukal      03/10/03 - NT emctl needs explicit option to get exit code
#    dmshah      01/22/03 - Fixing the return code issue with emdctl
#    aaitghez    08/28/02 - aaitghez_add_upload_info_matric
#    aaitghez    08/21/02 - Creation
# 

require "emd_common.pl";

EMD_PERL_DEBUG("Args are @ARGV");

my $emdroot = $ARGV[0];
my $emdctl = $emdroot."/bin/emdctl";
my $cmd = "$emdctl status agent";

EMD_PERL_DEBUG("cmd is $cmd");

#Following env variable is required for NT to return correct exit code
#No harm done to other platforms if this env. variable is present.
$ENV{NEED_EXIT_CODE} = 1;

my $output = `$cmd`;
my $exit_value = $? >> 8;

EMD_PERL_DEBUG("The exit code from emctl status agent is : $exit_value");


# 
# The return status codes are defined in nmectl/if/nmectl.h
# 

my $agentRunning = 3;
my $agentNotReady = 4;
my $successCode = 0;

if($exit_value != $agentRunning and 
   $exit_value != $agentNotReady and
   $exit_value != $successCode)
{
  EMD_PERL_DEBUG("Exiting with exit code : $exit_value");
  print "em_error=failed to get upload statistics: $!\n";
  exit $exit_value;
}

# parse the output to get what we want
my @lines = split("\n", $output);

# go through the output
foreach $line (@lines)
{
  EMD_PERL_DEBUG("Processing status agent output line: $line");
  $_ = $line;
  print "$line\n";
  #look for number of files pending upload
  if(m/Number of XML files pending upload/)
  {
      ($temp, $numfiles) = split(":",$line);
      $numfiles =~ s/\s//g;
  } 
  elsif (m/Size of XML files pending upload/)
  {
      ($temp, $sizefiles) = split(":",$line);
      $sizefiles =~ s/\s//g;
  }
  elsif (m/Last successful upload/)
  {
      ($a, $lastupload) = m/([a-zA-Z]*):(.*)/;
      $lastupload =~ s/\s//; 
  }elsif (m/Total Megabytes of XML files uploaded so far/)
  {
      ($temp, $totaluploaded) = split(":",$line);
      $totaluploaded =~ s/\s//g;
  }
}

EMD_PERL_DEBUG("numfiles=$numfiles,sizefiles=$sizefiles,lastupload=$lastupload\
,totaluploaded=$totaluploaded");
print "em_result=$numfiles|$sizefiles|$lastupload|$totaluploaded\n";