#!/usr/bin/env perl
use strict;
use warnings;
use SMT::Agent::Utils;
use XML::XPath;
use XML::XPath::XMLParser;

sub jobhandler
{
  my ($jobtype, $jobid, $args, $verbose) =  @_;

  SMT::Agent::Utils::logger ("jobhandler for execute called", $jobid);
  SMT::Agent::Utils::logger ("execute runs jobid \"$jobid\"", $jobid);

  # check whether this handler can handle requested jobtype
  SMT::Agent::Utils::error ("wrong job handler: \"execute\" cannot handle \"$jobtype\"", $jobid) if ( $jobtype ne "execute" );

  my $xpQuery = XML::XPath->new(xml => $args);
  eval { SMT::Agent::Utils::error("no argument section found for this job", $jobid) unless ( $xpQuery->exists('/arguments[1]')); };
  my $argSet;
  eval { $argSet = $xpQuery->find('/arguments[1]') };
  SMT::Agent::Utils::error("xml data is not parsable", $jobid) if ($@);
  SMT::Agent::Utils::error("too many argument sections found for this job", $jobid) unless ( (defined $argSet) && ($argSet->size() == 1) );
  my $arg = $argSet->pop();
  my @cmds = ();
  push @cmds, $arg->getAttribute('command');
  my $cmdSet;
  eval { $cmdSet = $xpQuery->find('/arguments[1]/options[1]/command[1]') };
  SMT::Agent::Utils::error("xml data is not parsable", $jobid) if ($@);
  foreach my $_n ($cmdSet->get_nodelist()) {
      push (@cmds, $_n->string_value()) if (defined $_n);
  }

  my $jobcommand = undef;
  foreach my $_c (@cmds) {
      if ( (defined $_c) && ($_c !~ /^$/) ) {
          $jobcommand = $_c;
          last;
      }
  }
  $jobcommand = '/bin/false' unless defined $jobcommand;

  #==  run bash ==
  my $command = "/bin/bash";
  my @cmdArgs;
  push (@cmdArgs, "-c");
  push (@cmdArgs, $jobcommand);

  (my $retval, my $stdout, my $stderr) = SMT::Agent::Utils::executeCommand ( $command, undef, @cmdArgs );

  return (
    stdout => ((defined $stdout) && $verbose) ? $stdout : '',
    stderr => ((defined $stderr) && $verbose) ? $stderr : '',
    exitcode => $retval,
    success => ($retval == 0 ) ? "true" : "false",
    message => ($retval == 0 ) ? "execute successfully finished" : "execute failed"
  );

}

SMT::Agent::Utils::logger ("successfully loaded handler for jobtype \"execute\"");

return 1;

