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

if ( ! SMT::Agent::Utils::openLock("smt-agent") )
{
  SMT::Agent::Utils::error ("Cannot open Lock. Process still running?");
}

# check if we run on an SMT server and if yes, check if we are allowed to run smt-client
if ( -f '/usr/sbin/smt' || -f '/etc/smt.conf')
{
    SMT::Agent::Utils::logger("Started smt-client on SMT server.");
    my $cfg = undef;
    eval {
        require SMT::Utils;
        $cfg = SMT::Utils::getSMTConfig();
    };
    if($@ || !defined $cfg)
    {
        SMT::Agent::Utils::error("Could not load SMT server configuration to find out if smt-client is allowed to run. Thus exiting.");
    }

    my $allowRegister = $cfg->val("LOCAL", "forwardRegistration");
    if (!(defined $allowRegister && $allowRegister eq "true"))
    {
        SMT::Agent::Utils::logger("Not allowed to run smt-client on this SMT server. The configuration 'forwardRegistration' is disabled in the SMT server config: /etc/smt.conf .");
        exit 0;
    }
}


my $jobid;
my $breakloop = 0;

my ($retval, $stdout, $stderr);
while( (! $breakloop) &&  defined ( $jobid = SMT::Agent::RestXML::parsejobid( SMT::Agent::RestXML::getnextjob() )))
{
  # prevent command injection
  SMT::Agent::Utils::error ( "cannot run jobs with non-numeric jobid." ) unless ( $jobid =~ /^[0-9]+$/ );
  SMT::Agent::Utils::logger ("running job $jobid", $jobid);
  ($retval, $stdout, $stderr) = undef;
  ($retval, $stdout, $stderr) = SMT::Agent::Utils::executeCommand ( SMT::Agent::Constants::PROCESSJOB, undef, ( $jobid ) );
  # return values of processjob script:
  #  0 : success
  #  1 : error -> report error and exit
  #  8 : success but break the smt-agent loop
  if ( $retval == 0 )
  {
      SMT::Agent::Utils::logger("job $jobid finished successfully, see job message for details");
  }
  elsif ( $retval == 8 )
  {
      SMT::Agent::Utils::logger("info: the smt-agent loop was stopped by job $jobid");
      $breakloop = 1;
  }
  else
  {
      SMT::Agent::Utils::error("error: job $jobid exited with $retval. stdout: '$stdout' stderr: '$stderr'", $jobid);
      # implicit exiting
  }

  sleep (3);
}

SMT::Agent::Utils::logger("no jobs left. exit.") unless (defined $retval && $retval =~ /^8$/);

if ( ! SMT::Agent::Utils::unLock("smt-agent") )
{
  SMT::Agent::Utils::error ("Cannot remove Lock.");
}


