#!/usr/bin/perl -w
#
# ecaccess-job-submit: Submit a new ECaccess Job
#
# Laurent.Gougeon@ecmwf.int - 2010-10-15

use ECMWF::ECaccess;
use Getopt::Long;
use Pod::Usage;
use File::Basename;

my %opt = (
	distant        => 0,
	encrypt        => 0,
	bufsize        => 524288,
	scheduledDate  => undef,
	noDirectives   => 0,
	gateway        => undef,
	remote         => undef,
	transferOutput => 0,
	transferError  => 0,
	transferInput  => 0,
	keep           => 0,
	eventIds       => undef,
	sterr2Stdout   => 0,
	noRenew        => 0,
	mailTo         => undef,
	onStart        => 0,
	onSuccess      => 0,
	onFailure      => 0,
	onRetry        => 0,
	queueName      => undef,
	jobName        => undef,
	manPage        => undef,
	lifeTime       => 7,
	retryCount     => 0,
	retryFrequency => 600,
	version        => 0,
	help           => 0,
	manual         => 0,
	retry		   => 0,
	debug          => 0
);

pod2usage( -noperldoc => 1, -exit => 1, verbose => 1 ) if !GetOptions(
	\%opt,
	qw(
	  distant
	  encrypt
	  bufsize=i
	  scheduledDate|at=s
	  noDirectives|nd
	  gateway|tg=s
	  remote|tr=s
	  transferOutput|to
	  transferError|te
	  transferInput|ti
	  keep|tk
	  eventIds|ni=s
	  sterr2Stdout|eo
	  noRenew|ro
	  mailTo|mu=s
	  onStart|mb
	  onSuccess|me
	  onFailure|mf
	  onRetry|mr
	  queueName=s
	  jobName|jn=s
	  manPage|mp=s
	  lifeTime|lt=i
	  retryCount|rc=i
	  retryFrequency|rf=i
	  version
	  help|?
	  manual|man
	  retry=i
	  debug
	  )
);

# Display version if requested
die ECMWF::ECaccess->VERSION . "\n" if ( $opt{version} );

my $source = $ARGV[0];

pod2usage( -noperldoc => 1, -exit => 1, verbose => 1 ) if ( $opt{help} );
pod2usage( -noperldoc => 1, -exit => 1, verbose => 2 ) if ( $opt{manual} );
pod2usage( -noperldoc => 1, -exit => 1, verbose => 0, -msg => "No source specified!\n" ) if not($source);
pod2usage( -noperldoc => 1, -exit => 1, verbose => 0, -msg => "Source is not a plain text file!\n" ) if not( $opt{distant} ) && not( -f $source && -T $source );
pod2usage( -noperldoc => 1, -exit => 1, verbose => 0, -msg => "Invalid -retryCount specified (>0)!\n" )     if not( $opt{retryCount} >= 0 );
pod2usage( -noperldoc => 1, -exit => 1, verbose => 0, -msg => "Invalid -retryFrequency specified (>0)!\n" ) if not( $opt{retryFrequency} > 0 );
pod2usage( -noperldoc => 1, -exit => 1, verbose => 0, -msg => "Invalid -lifeTime specified (>0)!\n" )       if not( $opt{lifeTime} > 0 );

# Create the ECaccess Controler
my $ecaccess = ECMWF::ECaccess->new( $opt{retry}, $opt{debug});

# Get the Token (using the Certificate in $HOME)
my $token = $ecaccess->getToken();

# Get the Control Channel
my $controlChannel = $ecaccess->getControlChannel();

# If the jobName options is not set then let's use the name of the input file
my $jobName;
if ( not( $opt{jobName} ) ) {
	$jobName = basename($source);
} else {
	$jobName = $opt{jobName};
}

# If the file is local then transfer it first
if ( not( $opt{distant} ) ) {

	# Get the Data Channel
	my $dataChannel = $controlChannel;
	if ( not $opt{encrypt} ) {
		$dataChannel = $ecaccess->getDataChannel();    # Plain Text rather than SSL (faster)
	}

	# Upload the file
	open FILE, $source or die "Error opening file: " . $source . "\n";
	$source = $controlChannel->getTemporaryFile($token)->result;
	my $handle = $controlChannel->getOutputFileHandle( $token, $source, 0, 640 )->result;
	while ( read( FILE, $data, $opt{bufsize} ) > 0 ) {
		$dataChannel->writeStringHandle( $handle, $data );
	}

	# Close handles
	$controlChannel->closeHandle($handle);
	close FILE;
} else
{

	# Copy the ECaccess file to a temporary file
	my $sourceECaccessFile = $source;
	$source = $controlChannel->getTemporaryFile($token)->result;
	$controlChannel->copyFile( $token, $sourceECaccessFile, $source, SOAP::Data->type( boolean => '0' ) );
}

# Submit the Job
$jobId = $controlChannel->submitJob(
	$token,
	SOAP::Data->name(
		"request" => \SOAP::Data->value(
			SOAP::Data->name( 'scheduledDate'          => $opt{scheduledDate} ),
			SOAP::Data->name( 'userMailAddress'        => $opt{mailTo} ),
			SOAP::Data->name( 'sendMailOnStart'        => $opt{onStart} ? 'true' : 'false' )->type('xsd:boolean'),
			SOAP::Data->name( 'sendMailOnSuccess'      => $opt{onSuccess} ? 'true' : 'false' )->type('xsd:boolean'),
			SOAP::Data->name( 'sendMailOnFailure'      => $opt{onFailure} ? 'true' : 'false' )->type('xsd:boolean'),
			SOAP::Data->name( 'sendMailOnRetry'        => $opt{onRetry} ? 'true' : 'false' )->type('xsd:boolean'),
			SOAP::Data->name( 'containsDirectives'     => $opt{noDirectives} ? 'false' : 'true' )->type('xsd:boolean'),
			SOAP::Data->name( 'queueName'              => $opt{queueName} ),
			SOAP::Data->name( 'name'                   => $jobName ),
			SOAP::Data->name( 'transferGatewayName'    => $opt{gateway} ),
			SOAP::Data->name( 'transferRemoteLocation' => $opt{remote} ),
			SOAP::Data->name( 'transferOutputFile'     => $opt{transferOutput} ? 'true' : 'false' )->type('xsd:boolean'),
			SOAP::Data->name( 'transferErrorFile'      => $opt{transferError} ? 'true' : 'false' )->type('xsd:boolean'),
			SOAP::Data->name( 'transferInputFile'      => $opt{transferInput} ? 'true' : 'false' )->type('xsd:boolean'),
			SOAP::Data->name( 'transferKeepInSpool'    => $opt{keep} ? 'true' : 'false' )->type('xsd:boolean'),
			SOAP::Data->name( 'renewSubscription'      => $opt{noRenew} ? 'false' : 'true' )->type('xsd:boolean'),
			SOAP::Data->name( 'errorToOutput'          => $opt{sterr2Stdout} ? 'true' : 'false' )->type('xsd:boolean'),
			SOAP::Data->name( 'manPageContent'         => $opt{manPage} ),
			SOAP::Data->name( 'lifeTime'               => $opt{lifeTime} ),
			SOAP::Data->name( 'retryCount'             => $opt{retryCount} ),
			SOAP::Data->name( 'retryFrequency'         => $opt{retryFrequency} ),
			SOAP::Data->name( 'eventIds'               => $opt{eventIds} ),
			SOAP::Data->name( 'inputFile'              => $source )
		)
	)
)->result;
print $jobId. "\n";

# Delete the temporary file
$controlChannel->deleteFile( $token, $source, SOAP::Data->type( boolean => '1' ) );

# Logout
$ecaccess->releaseToken($token);

__END__

=head1 NAME

ecaccess-job-submit - Submit a new ECaccess Job

=head1 SYNOPSIS

B<ecaccess-job-submit -version|-help|-manual>

B<ecaccess-job-submit [-debug] [-distant] [-encrypt] [-bufsize> I<length>B<] [-scheduledDate> I<date>B<]
[-noDirectives] [-gateway> I<name>B<] [-remote> I<location>B<] [-transferOutput] [-transferError]
[-transferInput] [-keep] [-eventIds> I<list>B<] [-sterr2Stdout] [-noRenew] [-mailTo> I<email>B<]
[-onStart] [-onSuccess] [-onFailure] [-onRetry] [-jobName> I<name>B<] [-manPage> I<content>B<]
[-lifeTime> I<days>B<] [-retryCount> I<number>B<] [-retryFrequency> I<frequency>B<] [-queueName> I<name>B<]>
I<source>

=head1 DESCRIPTION

Allow submitting the I<source> script on either the default ECaccess batch queue or the ECaccess batch queue
specified with the I<-queueName> option. ECaccess batch queue name can be obtained with the B<ecaccess-queue-list>
command (the default queue is the first in the list).

A special service (see option B<-eventIds>) allows to automatically submit jobs to be run when certain points in the daily
ECMWF operational forecast suite have been reached. The main purpose is to ensure that certain data is available before
e.g. submitting a MARS request. These events correspond to the different stages when the ECMWF operational activity
has produced certain data or products. The list of events can be retrieved with the B<ecaccess-event-list> command.

In order to facilitate the migration from the old ECtools (ecjreq/ecjput commands) the equivalents options can be set using
their old names (e.g. B<-at> for B<-scheduledDate>). This should limit the scripts modifications for job submissions.

=head1 ARGUMENTS

=over 8

=item I<source>

The name of the file which contains the job input script (depending of the -distant
option this file is either at ECMWF or local to your workstation).

=back

=head1 OPTIONS

=over 8

=item B<-distant>

By default the I<source> is specifying a file which is local to your workstation. Using this option
allow submitting a script which is already at ECMWF.

=item B<-encrypt>

By default the I<source> file is uploaded through the plain text channel (http).
Using this option will force the upload to occurs through the SSL secure
channel (https). This option only apply for local scripts (no B<-distant>).

=item B<-bufsize> I<length>

Specify the I<length> of the buffer (in bytes) which is used to upload the file.
The larger the buffer the smaller the number of http/s requests. By default a
buffer of 524288 bytes (512KB) is used. This option only apply for local scripts
(no B<-distant>).

=item B<-at, -scheduledDate> I<date>

Allow specifying the start I<date> for the Job. By default the job will start
as soon as possible. The format for the date is 'yyyy-MM-dd HH:mm'.

=item B<-nd, -noDirectives>

Allow submitting a job with no scheduler directives. Some default directives
will be added to your input script to allow processing the job.

=item B<-tg, -gateway> I<name>

This is the I<name> of the target ECaccess Gateway for the transfers. It is by default
the Gateway you are connected to. In order to get the name of your current Gateway you
can use the B<ecaccess-gateway-name> command. When using the commands at ECMWF the
default Gateway is always "ecaccess.ecmwf.int".

=item B<-tr, -remote> I<location>

Defines the target ECtrans I<location> in the format I<association-name>B<[>I<@protocol>B<]>.

=item B<-to, -transferOutput>

Request the transfer of the job standard output to the gateway and remote location defined
in the B<-gateway> and B<-remote> options.

=item B<-te, -transferError>

Request the transfer of the job error output to the gateway and remote location defined
in the B<-gateway> and B<-remote> options.

=item B<-ti, -transferInput>

Request the transfer of the job input to the gateway and remote location defined
in the B<-gateway> and B<-remote> options.

=item B<-tk, -keep>

Allow keeping the transfers requests in the spool.

=item B<-ni, -eventIds> I<list>

Allow giving a I<list> of event-identifiers to subscribe to with the Job. The list should
be separated by ';' or ','.

=item B<-eo, -sterr2Stdout>

Force redirection of the job standard error output (stderr) to the job standard output (stdout).

=item B<-ro, -noRenew>

The job subscriptions to events will not be renewed.

=item B<-mu, -mailTo> I<email>

Defines the target I<email> address (default: current ECMWF user identifier).

=item B<-mb, -onStart>

Allow sending a mail when the execution/transfer begins.

=item B<-me, -onSuccess>

Allow sending a mail when the execution/transfer ends.

=item B<-mf, -onFailure>

Allow sending a mail when the execution/transfer fails.

=item B<-mr, -onRetry>

Allow sending a mail when the execution/transfer retries.

=item B<-queueName> I<name>

The name of the ECaccess batch queue to submit the job to.

=item B<-jn, -jobName> I<name>

Allow specifying a I<name> for the new Job (other than the Job Identifier). If no name
is specified then the name of the input script is used.

=item B<-mp, -manPage> I<content>

Allow giving the man page I<content> which will be displayed to the ECMWF operators in
case of problems with your Job (e.g. what to do or who to contact).

=item B<-lt, -lifeTime> I<days>

Allow specifying the job input/output life time in I<days>. The default is 7 days.

=item B<-rc, -retryCount> I<number>

Defines the I<number> of retries. The default is 0.

=item B<-rf, -retryFrequency> I<frequency>

Defines the I<frequency> of retries in seconds. The default is 600 seconds.

=item B<-version>

Display version number and exits.

=item B<-help>

Print a brief help message and exits.

=item B<-manual>

Prints the manual page and exits.

=item B<-retry> I<count>

Number of SSL connection retries per 5s to ECMWF. This parameter only apply to the
initial SSL connection initiated by the command to the ECMWF server. It does not
apply to all the subsequent requests made afteward as it is mainly targeting errors
that can happen from time to time during the SSL handshake. Default is no retry.

=item B<-debug>

Display the SOAP and SSL messages exchanged.

=back

=head1 EXAMPLES

B<ecaccess-job-submit -noDirectives> I<./test.txt>

Transfer the local file I<test.txt> to your ECMWF spool and submit the job to the default ECaccess batch queue.
The source does not have any directives.

=head1 SEE ALSO

B<ecaccess-queue-list>, B<ecaccess-event-list>, B<ecaccess-job-delete>, B<ecaccess-job-get>, B<ecaccess-job-list>
B<ecaccess-job-restart> and B<ecaccess>.

=cut
