#!/usr/bin/env perl
use strict;
use warnings;
use SMT::Agent::Constants;
use SMT::Agent::Config;
use SMT::Agent::Utils;
use SMT::Agent::RestXML;


###############################################################################
# load job handler
# args: jobtype, jobid
sub loadjobhandler
{
  my ( $jobtype, $jobid) =  @_;

  # prevent command injection
  SMT::Agent::Utils::error ( "cannot load non-alphanumeric jobs." ) unless ( $jobtype =~ /^[0-9A-Za-z]+$/ );

  my $jobhandler = SMT::Agent::Constants::JOB_HANDLER_PATH."/".$jobtype;

  eval { require $jobhandler };
  SMT::Agent::Utils::error( "unable to load handler for jobtype \"$jobtype\": $@", $jobid ) if ( $@ );
}


my  $jobid  =  $ARGV[0];
SMT::Agent::Utils::logger ( "jobid: $jobid" );

my $xmldata = SMT::Agent::RestXML::getjob( $jobid );
my %jobdata = SMT::Agent::RestXML::parsejob( $xmldata );
my $ret;
my %retval;

# always allow the job type servererror
if ( (not SMT::Agent::Utils::isAgentAllowed($jobdata{type}))  &&  ($jobdata{type} ne 'servererror') )
{
  SMT::Agent::Utils::logger("Running ". $jobdata{type}. " denied by client policy", $jobdata{id} );
  $ret = SMT::Agent::RestXML::updatejob ( $jobdata{id}, 3 , "denied by client policy", "", "", "", undef );
}
else
{
  loadjobhandler ( $jobdata{type}, $jobdata{id} );

  my $verbose = (defined $jobdata{verbose} && ($jobdata{verbose} =~ /^1$/ || $jobdata{verbose} =~ /^true$/)) ? 1 : 0;

  %retval = jobhandler ( $jobdata{type}, $jobdata{id}, $jobdata{args}, $verbose );

  if ($verbose)
  {
    SMT::Agent::Utils::logger ( "job ". $jobdata{id}. " stdout: ".$retval{stdout}, $jobdata{id} );
    SMT::Agent::Utils::logger ( "job ". $jobdata{id}. " stderr: ".$retval{stderr}, $jobdata{id} );
  }
  SMT::Agent::Utils::logger ( "job ". $jobdata{id}. " message: ".$retval{message}, $jobdata{id} );
  SMT::Agent::Utils::logger ( "job ". $jobdata{id}. " exitcode: ".$retval{exitcode}, $jobdata{id} );
  SMT::Agent::Utils::logger ( "job ". $jobdata{id}. " statuscode: ".$retval{success}, $jobdata{id} );

  # transform success messages to IDs;
  #   0 is no reasonable success ID, thus it should also map to 2 (failed) like 'undef', (0 might lead to an infinit loop)
  #   all other IDs pass as they are, as there might be new IDs introduced
  my $success = $retval{success} || 2;
  $success = 1 if $success =~ /^true$/;
  $success = 2 if $success =~ /^false$/;
  $success = 2 if $success !~ /^\d+$/;

  $ret = SMT::Agent::RestXML::updatejob( $jobdata{id}, $success, $retval{message}, $retval{stdout}, $retval{stderr}, $retval{exitcode}, $retval{result} );
}

# pass server failures via exit code to prevent infinit loops one layer above
my $exitcode = (($ret) ? 0:1);
$exitcode = 8 if (exists $retval{breakloop} && defined $retval{breakloop} && $retval{breakloop} =~ /^true$/);
exit $exitcode;

