#!/bin/bash 

# NOTE:
#   EXE : rwapper.sh 
#   TASK_ID     : Id of the task
#   SCRATCH_DIR : EACH task has its own scratch directory
#   SCRIPT_DIR  : Script is identical for each task => Same directory for ALL tasks
#   OUT_DIR     : EACH task has its own output directory

# This script may be a bit too complicated for those who can run their
# calculations in the same directory. If that is the case, then simply run as
# Rscript myScript.r $1 > $TASK_ID.out 2>&1
# $1=$TASK_ID is the argument to myScript.r, which lets us differentiate the 
# independent calculations

# Retrieve variable from the command line
START_DIR=$PWD
EXE=$0
TASK_ID=$1
SCRATCH_DIR=$2
SCRIPT_DIR=$3
OUT_DIR=$4

if [ "$#" -ne 4 ] ; then
     echo "  ERROR: Command line needs 4 parameters"
     echo "  Current arg list: $@"
else
     echo "  TaskID:$TASK_ID started at `date`"
     mkdir -p $SCRATCH_DIR  
     cd $SCRATCH_DIR
     # Copy content SCRIPT_DIR to SCRATCH_DIR
     cp -pR $SCRIPT_DIR/* . 
     Rscript mcex.r  > $TASK_ID.out 2>&1

     # Copy results back to OUT_DIR
     mkdir -p $OUT_DIR
     cp -pR * $OUT_DIR
     cd $START_DIR
     rm -rf $SCRATCH_DIR
     echo "  TaskID:$TASK_ID ended at `date`"
fi
