#!/usr/bin/env perl


###################################################
# This script adds jobs to arc-queue. It is the 
# companion script to arc-qrunner.
# -- Dan Marcus 2.28.03
###################################################


use FindBin qw($Bin);
use lib "$Bin";
my $ARC_TOOLS = "/home/vmuser/arc-queue";

use strict;


#open log file --  standard out is directed to it!
my $log = "$ARC_TOOLS/logs/arc-qadd.log";
open STDOUT, ">>$log" or fail("The log file ($log) could not be opened");
$| = 1;  #keeps things from being buffered.

#open error log file --  standard error is directed to it!
my $error = "$ARC_TOOLS/logs/arc-qadd.error";
open STDERR, ">>$error" or fail("The error file ($error) could not be opened");
$| = 1;  #keeps things from being buffered.

print "\n\n------------------------------------------------\n";
print scalar localtime;
print STDOUT "@ARGV\n";
print "\n";

print STDERR "\n\n------------------------------------------------\n";
print STDERR scalar localtime;
print STDERR "\n";



#exclusive lock arc-queue
open QUEUE, ">>$ARC_TOOLS/arc-queue" or fail("FAILURE: Coulnd't open queue file.\n");
lockIt();

#put all of the elements in the file queue into an array.
my @arry = fixArgs(@ARGV);
print QUEUE "@arry\n";


#unlock arc-queue
    unlock();


my $LOCK_SH = 1;
my $LOCK_EX = 2;
my $LOCK_NB = 4;
my $LOCK_UN = 8;

sub lockIt() {
    flock QUEUE, $LOCK_EX;
    #seek QUEUE, 0, 2;
}

sub unlock(){
    flock QUEUE, $LOCK_UN;
}

sub fail(){
    my $failMessage = shift @_;
    print $failMessage;
    die;
}

sub fixArgs() {
  my @args =  @_;
  my @rtn = ();
  my $length = @args;
  my $i=0;
  for ($i=0; $i < $length;$i++) {
      push @rtn, escapeShellCharacters($args[$i]); 
  }
  return @rtn;
}

sub escapeShellCharacters() {
   my $command = shift @_;
   $command =~s/\\/\\\\/g;
   $command =~s/\"/\\\"/g;
   $command =~s/{/\\{/g;
   $command =~s/}/\\}/g;
   $command =~s/\'/\\\'/g;
   $command =~s/\`/\\\`/g;
   $command =~s/\?/\\?/g;
   $command =~s/\[/\\[/g;
   $command =~s/\]/\\]/g;
   $command =~s/~/\\\~/g;
   $command =~s/\$/\\\$/g;
   $command =~s/\!/\\\!/g;
   $command =~s/\&/\\\&/g;
   $command =~s/;/\\\;/g;
   $command =~s/\(/\\\(/g;
   $command =~s/\)/\\\)/g;
   $command =~s/>/\>/g;
   $command =~s/!/\!/g;
   $command =~s/\#/\\#/g;
   return $command;
}




