#!/bin/ksh

### GAD PIPELINE ###
## wrapper_run_outrider.sh
## Description : a wrapper for qsubing run_outrider.R script
## Usage : qsub -pe smp 1 -v MATRIX=</path/to/the/batch/count/matrix>,DESIGN=</path/to/the/design/file>,OUTPUTDIR=</path/to/the/output/directory>,[LOGFILE=/path/to/the/log/file],[CONFIGFILE=/path/to/the/config/file] wrapper_run_outrider.sh
## Output : run_outrider.R output
## Requirements : R, outrider package, matrix file

## Author : yannis.duffourd@u-bourgogne.fr
## Creation Date : 20201021
## last revision date : 20201022
## Known bugs : None

#$ -q batch
#$ -V

# TODO: log with design file name
# Log file path option
if [ -z ${LOGFILE} ]
then
    LOGFILE=run_outrider.$(date +"%F_%H-%M-%S").log
fi

# Config file path option
if [ -z ${CONFIGFILE} ]
then
    CONFIGFILE=analysis_config.tsv
fi

# design file path option
if [ ! -f  ${DESIGN} ]
then
  echo "Design file does not exist"
  echo "$(date +"%F_%H-%M-%S"): END"
  touch wrapper_run_outrider.failed
  exit 1
fi

# matrix file path option
if [ ! -f  ${MATRIX} ]
then
  echo "Matrix file does not exist"
  echo "$(date +"%F_%H-%M-%S"): END"
  touch wrapper_run_outrider.failed
  exit 1
fi

# Check if output dir exist
if [ -z ${OUTPUTDIR} ]
then
    echo "Output Directory does not exist"
    echo "$(date +"%F_%H-%M-%S"): END"
    touch wrapper_run_outrider.failed
    exit 1
fi



PIPELINEBASE=`grep pipelinebase $CONFIGFILE | cut -f2`
RSCRIPT=`grep rscrna $CONFIGFILE | cut -f2`

source activate leafcutter
source $PIPELINEBASE/common/splice/load_leafcutter_env.sh

# Logging
exec 1>> $LOGFILE 2>&1
echo "$(date +"%F_%H-%M-%S"): START"

# Launch R script command and check exit code
echo "Command : $RSCRIPT $PIPELINEBASE/common/DE/run_outrider.R $MATRIX $DESIGN $OUTPUTDIR"
$RSCRIPT $PIPELINEBASE/common/DE/run_outrider.R $MATRIX $DESIGN $OUTPUTDIR
exit_code=$?
echo "run_outrider.R exit code : $exit_code"
if [ $exit_code != 0 ]
then
    echo "$(date +"%F_%H-%M-%S"): END"
    touch wrapper_run_outrider.failed
    exit 1
fi

echo "$(date +"%F_%H-%M-%S"): END"