#!/usr/bin/env perl

use warnings;
use strict;
use File::Spec;
use File::Basename;
use Cwd;

use sigtrap 'handler' => \&HandleDeath, 'normal-signals';
sub HandleDeath { return @_; }

#using this expression gives you the user-friendly name of the mounted directory we're in
my $cwd = `echo pwd | bash`;
chomp $cwd;

my $commands_file = "";
my $options = "";

# Parse arguments:
# 
# -If there is one argument, it is the file of commands
# -If there are two arguments, the first is the commands file
# and the second is options for qsub
#
if (@ARGV < 1) {
    die("Usage: distribute.pl <command-file> [optional-qsub-options]\n");
} elsif (@ARGV > 1) {
    $options = $ARGV[1];
}

$commands_file = $ARGV[0];

open(IN,$commands_file) || die "Couldn't open file $commands_file for reading\n";
my @commands = <IN>;
close(IN);

my $numJobs = $#commands + 1;
my ($jobName,undef) = split /\s+/, $commands[0];
$jobName = basename $jobName;

my $sge = $cwd . "/SGE";
mkdir $sge if (!-e $sge);

my $scriptName = "$sge/job." . gen_unique_id();
foreach my $el (0..$#commands) {
  #$commands[$el] =~ s/\'/\\\'/g;
  $commands[$el] =~ s/ \.\// $cwd\//g;
  $commands[$el] =~ s/ \.\.\// $cwd\/\.\.\//g;
  $commands[$el] =~ s/^\.\.\//$cwd\/\.\.\//g;
  writeScriptWithHeader($scriptName . "." . ($el+1),$commands[$el]);
}
writeScript($scriptName,"$scriptName.\$SGE_TASK_ID");

my $command_line;

$command_line = "qsub $options -t 1-$numJobs -sync y -e $sge -o $sge -N $jobName $scriptName";
#$command_line = "qsub $options -t 1-$numJobs -sync y -N $jobName $scriptName";

print "submitted: $command_line\n";
print `$command_line`;

sub writeScriptWithHeader{
  my ($scriptName,$command) = @_;

  chomp $command;
  open FILE, "> $scriptName";
  print FILE "#!/bin/bash\n\n";
  print FILE "cd $cwd\n";
  print FILE 'echo "================================================================"', "\n";
  print FILE 'echo JOB_NAME=$JOB_NAME', "\n";
  print FILE 'echo JOB_ID=$JOB_ID', "\n";
  print FILE 'echo JOB_HOST=`hostname`', "\n";
  print FILE 'echo SGE_TASK_ID=$SGE_TASK_ID', "\n";
  print FILE 'echo DATE=`date`', "\n";
  print FILE 'echo NSLOTS=$NSLOTS', "\n";
  print FILE 'echo QUEUE=$QUEUE', "\n";
  print FILE 'echo PATH=$PATH', "\n";
  print FILE 'echo SGE_STDIN_PATH=$SGE_STDIN_PATH', "\n";
  print FILE 'echo SGE_STDOUT_PATH=$SGE_STDOUT_PATH', "\n";
  print FILE 'echo SGE_STDERR_PATH=$SGE_STDERR_PATH', "\n";
  print FILE "echo script name generated by distribute.pl = $scriptName\n";
  print FILE "echo command:  '$command'\n";
  print FILE "echo '================================================================'\n";

  print FILE "$command\n";
  close FILE;
  chmod 0755, $scriptName;
}

sub writeScript{
  my ($scriptName,$command) = @_;

  chomp $command;
  open FILE, "> $scriptName";
  print FILE "#!/bin/bash\n\n";
  print FILE "cd $cwd\n";
  print FILE "$command\n";
  close FILE;
  chmod 0755, $scriptName;
}

sub gen_unique_id{
  my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
  my $datetime = sprintf("%04d-%02d-%02d.%02d-%02d-%02d",$year+1900,$mon+1,$mday,$hour,$min,$sec);
  my $count = 0;
  my $filename = "$datetime.$$";
  while (glob "*.$filename") {
    $count += 1;
    $filename = "$datetime.$$.$count";
  }
  return $filename;
}
