#!/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 eject called", $jobid);
  SMT::Agent::Utils::logger ("eject runs jobid \"$jobid\"", $jobid);

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

  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 @actions = ();
  push @actions, $arg->getAttribute('action');
  my $actionSet;
  eval { $actionSet = $xpQuery->find('/arguments[1]/options[1]/action[1]') };
  SMT::Agent::Utils::error("xml data is not parsable", $jobid) if ($@);
  foreach my $_n ($actionSet->get_nodelist()) {
      push (@actions, $_n->string_value()) if (defined $_n);
  }

  my $action = undef;
  foreach my $_a (@actions) {
      if ( (defined $_a) && ($_a !~ /^$/) &&
           ($_a eq 'open' || $_a eq 'close' || $_a eq 'toggle')) {
          $action = $_a;
          last;
      }
  }
  $action = 'open' unless defined $action;

  #==  run eject ==
  my $command = "/usr/bin/eject";
  my @cmdArgs;
  push (@cmdArgs, "-T") if ( $action eq "toggle" );
  push (@cmdArgs, "-t") if ( $action eq "close" );

  (my $retval, my $stdout, my $stderr) = SMT::Agent::Utils::executeCommand ( $command, undef, @cmdArgs );
  SMT::Agent::Utils::error ("eject failed", $jobid) if ( $retval != 0 );

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

}

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

1;

