#!/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?");
}

my $jobid;

while( 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);
  (my $retval, my $stdout, my $stderr) = SMT::Agent::Utils::executeCommand ( SMT::Agent::Constants::PROCESSJOB, undef, ( $jobid ) );
  if ( $retval != 0) 
  {
  	SMT::Agent::Utils::logger ("warning: job $jobid exited with $retval. stdout: '$stdout' stderr: '$stderr'", $jobid);
  }

  sleep (3);
}

SMT::Agent::Utils::logger ("no jobs left. exit.");

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


