#!/usr/bin/perl -w

#
#       Configuration
#

use strict;
use Getopt::Std;
our ($opt_V,$opt_N,$opt_e,$opt_o,$opt_d,$opt_q);

my $CONDOR_DIR = "/home/condor/release/bin/" ;
my $TEMP_DIR = "/tmp" ;

#
#       Fonctions
#

sub uniqueId()
{
        my $length=16;
        my $uniqueId="";

        for(my $i=0 ; $i< $length;)
        {
                my $j = chr(int(rand(127)));

                if($j =~ /[a-zA-Z0-9]/)
                {
                        $uniqueId .=$j;
                        $i++;
                }
        }

        return $uniqueId;
}

#
#       Main
#

#Recuperation of args
getopts('VN:e:o:d:q:');

#print $opt_V,$opt_N,$opt_e,$opt_o,$opt_d,$opt_q;

# qsub -N pythia_run -e pythia.err -o pythia.log -d $main -V -q madgraph
# pythia.pbs >> ../running_jobs


my $path = `pwd`;
chomp ($path=$path);
my $executable = $path."\/".$ARGV[0];

#output
my $output = "/dev/null";
if(defined($opt_o))
{
        #print "debug\n";
        $output = $opt_o;
}

#print $output;

#error
my $error = "/dev/null";
if(defined($opt_e))
{
         $error = $opt_e;
}

#log
my $log = "/tmp/log_condor";

#condor arguments
my $arguments = " ";
my $requirements = "(MADGRAPH == True)";
my $queue = "1";

my $filename=$TEMP_DIR."/".uniqueId();

open (FILE,">$filename");

print FILE "#Submission file generated by pbs-condor wrapper\n";
#Initial diretory
if(defined($opt_d))
{
        print FILE "initialdir =" . $opt_d."\n";
}
else
{
        print FILE "initialdir =" . $path."\n";
}
print FILE "universe = vanilla\n";
print FILE "executable =" . $executable."\n";
print FILE "output =". $output."\n";
print FILE "error =" . $error."\n";
print FILE "log =" . $log."\n";
print FILE "arguments =" . $arguments."\n";
print FILE "requirements =" . $requirements."\n";
print FILE "queue =" . $queue."\n";
print FILE "notification = Never\n";

if($opt_V)
{
        print FILE "getenv = True\n";
}

close(FILE);

my $cmd = $CONDOR_DIR."/condor_submit ".$filename . ">".$filename.".out";
system($cmd);

my $cmd2 = "cat ".$filename.".out | tail -1 | cut -d \" \" -f 6 ";

my $rc = `$cmd2`;

my $index = index($rc,".");

system("rm -f ".$filename."*");

print substr($rc,0,$index)."\n";

