#Author: Kondayya Duvvuri
#Date Created: 05/05/2004
#Handles secure and getemhome options of emctl for agent.
#Revision History:
#  kduvvuri  - 05/07/2004 -- add ilint.
#  shianand  - 03/31/2005 -- Refactoring Secure Commands.
#  skuchero  - 07/17/2006 -- fix ilint.

package AgentMisc;
use EmctlCommon;
use EmCommonCmdDriver;
use English;
use File::stat;
use File::Copy;

sub new {
  my $classname = shift;
  my $self = {};
  bless ( $self, $classname );
  return $self;
}
sub doIT {
  my $classname = shift;
  my $rargs = shift;
  my $result = 0;
  my $argCount = @$rargs;

  if( $argCount == 0 )
  {
    return 2;  #UNKNOWN_CMD
  }
  
  if ( $rargs->[0] eq "getemhome" )
  {
    print "EMHOME=$ENV{EMHOME}\n";
  }
  elsif( $rargs->[0] eq "ilint")
  {
    runILINT($rargs);
  }
  else
  {
    my $found = 0;

    if ( $rargs->[1] eq "agent" )
    {
      $found = runExternalCmd($rargs); 
    }

    if ($found == 0)
    {
      $result = $EMCTL_UNK_CMD;
    }
  }
  return $result;
}


sub usage
{
  print "        emctl getemhome\n";
  print "        emctl ilint\n";
  
}

#
# get the perl script that runs
#
sub runExternalCmd()
{
  local (*args) = @_;

  my $found = 0;
  
  open(AGENTMISCMDS, "<$EMDROOT/bin/AgentMiscCmds") ||
                 return $found;
 
  while (my $cmdline = <AGENTMISCMDS> )
  {
    if ($cmdline =~ /^$args[0],/ )
    {
      $cmdline =~ s/^$args[0],//;
      shift(@args);
      shift(@args);
      $found = 1;

      my $rc = 0xffff && system("$ENV{PERL_BIN}/perl $cmdline @args"); 
      $rc >>= 8;

      if( $rc < 0 )
      {
        print stderr "Failed to execute $cmdline\n";
        close(AGENTMISCMDS);
        exit -1;
      }
      last;
    }
  }
  close(AGENTMISCMDS);

  return $found; 
}

#
# runILINT takes
# 1) Array of arguments
#
# ILINT performs static validation of the XML metadata:
# target, instance, and collection.

sub runILINT()
{
  use File::Spec qw( tmpdir );

  local (*args) = @_;

  die "Missing ilint executable"
     if (! -e "$EMDROOT/bin/nmei"."$binExt");

  # ilint requires that T_WORK env variable is set
  if (not defined $ENV{T_WORK})
  {
    $ENV{T_WORK} = File::Spec->tmpdir(); # /tmp on Linux, C:\TEMP on Windows
  }

  shift(@args); # -- shift out ilint...

  my $rc = 0xffff & system ("$EMDROOT/bin/nmei -e @args"); # ilint <args>
  $rc >>= 8;
  exit $rc;
}

1;
