#!/bin/ksh

### GAD PIPELINE ###
## wrapper_run_de_analysis.sh
## Description : a wrapper for qsubing run_de_analysis.R script
## Usage : qsub -pe smp 1 -v INPUTFILE=/path/to/the/matrix/file>,DESIGNFILE=</path/to/the/design/file>,OUTPUTDIR=</path/to/the/output/dir>,[BASENAME=analysis_basename],[TESTTYPE=et|qlf|lrt],[LOGFILE=/path/to/the/log/file],SAMPLE=[samplename],[CONFIGFILE=/path/to/the/config/file] wrapper_run_de_analysis.sh
## Output : run_de_analysis.R output
## Requirements : R, edgeR, limma

## Author : Emilie.Tisserant@u-bourgogne.fr
## Creation Date : 20170331
## last revision date : 20201110
## Known bugs : None

#$ -q batch
#$ -V

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

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

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

R_LIBS="/work/gad/shared/bin/R_libs"
export R_LIBS

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

# Check if config file exist
if [ ! -f $CONFIGFILE ]
then
    echo "Config file does not exist"
    echo "$(date +"%F_%H-%M-%S"): END"
    touch run_de_analysis.failed
    exit 1
fi

# Check if input file exist
if [ ! -f $INPUTFILE ]
then
    echo "Input file does not exist"
    echo "$(date +"%F_%H-%M-%S"): END"
    touch run_de_analysis.failed
    exit 1
fi

# Check if design file exist
if [ ! -f $DESIGNFILE ]
then
    echo "Design file does not exist"
    echo "$(date +"%F_%H-%M-%S"): END"
    touch run_de_analysis.failed
    exit 1
fi

# Check if output directory is specified
if [ -z $OUTPUTDIR ]
then
    echo "Output directory is not specified"
    echo "$(date +"%F_%H-%M-%S"): END"
    touch run_de_analysis.failed
    exit 1
fi

# Analysis basename option
if [ -z $BASENAME ]
then
    BASENAME="$SAMPLE.DE_analysis"
fi

# Method option
if [ -z $METHOD ]
then
    METHOD="limma"
fi

# Filter option
if [ -z $FILTER ]
then
    FILTER=1
fi

# Norm option
if [ -z $NORM ]
then
    NORM="TMM"
fi

# Launch R script command and check exit code
echo "Command: RSCRIPT $PIPELINEBASE/common/DE/run_de_analysis.R $INPUTFILE $DESIGNFILE $BASENAME $OUTPUTDIR/ $METHOD $FILTER $NORM"
$RSCRIPT $PIPELINEBASE/common/DE/run_de_analysis.R $INPUTFILE $DESIGNFILE $BASENAME $OUTPUTDIR/ $METHOD $FILTER $NORM
run_de_analysis_exitcode=$?
echo "run_de_analysis.R exit code : $run_de_analysis_exitcode"
if [ $run_de_analysis_exitcode != 0 ]
then
    echo "$(date +"%F_%H-%M-%S"): END"
    touch run_de_analysis.failed
    exit 1
fi

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