#!/usr/bin/perl -w

# usage : perl sm_STAR.pl <read1.fastq.gz> <read2.fastq.gz>
# 10/02/2014 - Wrapper du traitement des données RNAseq
# Sarah Maman
# Copyright (C) 2014 INRA
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
use strict;
use File::Basename;
use Getopt::Long;
use Config::IniFiles;

my $cfg = Config::IniFiles->new( -file => "/usr/local/bioinfo/src/galaxy-dev/galaxy-dist/PATH.ini" );
my $PATH = $cfg->val( 'workPath', 'FILEPATH_DEV' );
my $STAR = $cfg->val( 'toolsPath', 'STAR' );

my $Nthreads;
my $genome_path;
my $reads_selector;
my $input_read;
my $Read1fastqgz;
my $Read2fastqgz;
my $alignIntronMin;
my $alignIntronMax;   
my $outFilterMismatchNmax;
my $orientation;
my $outputfile;
my $outputlog;

Getopt::Long::Configure( 'no_ignorecase', 'bundling' );
GetOptions (
    'runThreadN=i' => \$Nthreads,
    'genomeDir=s' => \$genome_path,
    'readsselector=s'=> \$reads_selector,
    'readFilesIn1=s' => \$Read1fastqgz,
    'readFilesIn2=s' => \$Read2fastqgz,
    'readsinputread=s' => \$input_read,
    'alignIntronMin=i' => \$alignIntronMin,
    'alignIntronMax=i' => \$alignIntronMax,   
    'outFilterMismatchNmax=i' => \$outFilterMismatchNmax,
    'orientation=s' => \$orientation,
    'outputfile=s' => \$outputfile,
    'outputlog=s' => \$outputlog 
) or die "Usage: Error in command line arguments\n";

my $cmd1 = ''; my $cmd2 ='';my $cmd3 = ''; my $cmd4 ='';

#Récuperer le numero (unique) de l'output afin, si besoin, de créer un répertoire de travail unique dans /work/galaxy-dev/workspace
my ($nb) = ($outputfile=~/galaxy_dataset_(\d+)\.\S+$/);

#Repertoire de sortie cree par le script, verif des droits d'ecriture sur ce repertoire de sortie
`cd $PATH/; mkdir $nb/; chmod -R 777 $nb/; cd $nb/;`;
my $dirresults= "$PATH/".$nb;

if ($reads_selector eq "single"){
#Si besoin, recupération du fichier de configuration avec modification de l extension
`ln -s $input_read $dirresults/input_read.fastq.gz;`;

                if ($orientation eq "No"){
                    $cmd1 = "(cd $dirresults; $STAR --runThreadN $Nthreads --genomeDir $genome_path --readFilesIn $dirresults/input_read.fastq.gz --alignIntronMin $alignIntronMin --alignIntronMax $alignIntronMax --outFilterMismatchNmax $outFilterMismatchNmax --readFilesCommand zcat --outSAMstrandField intronMotif --outFileNamePrefix $nb) >& ./out_Star.log 2>&1";
                    system $cmd1;
                    #Info pour les biologistes
                    print STDOUT "STAR command run on cluster without oriented reads : \n\n $cmd1 \n\n ";
                }
                else
                {
                    $cmd2 = "(cd $dirresults; $STAR --runThreadN $Nthreads --genomeDir $genome_path --readFilesIn $dirresults/input_read.fastq.gz --alignIntronMin $alignIntronMin --alignIntronMax $alignIntronMax --outFilterMismatchNmax $outFilterMismatchNmax --readFilesCommand zcat --outSAMstrandField intronMotif --outFileNamePrefix $nb) >& ./out_Star.log 2>&1";
                     system  $cmd2;
                    #Info pour les biologistes
                    print STDOUT "STAR command run on cluster with oriented reads : \n\n $cmd2 \n\n 
                    Instead, you need to run Cufflinks with the library option --library-type options. For example, cufflinks <…> -library-type fr-firststrand should be used for the “standard” dUTP protocol. This option has to be used only for Cufflinks runs and not for STAR runs.\n\n";
                }
}else{
#Si besoin, recupération du fichier de configuration avec modification de l extension
`ln -s $Read1fastqgz $dirresults/Read1.fastq.gz; ln -s $Read2fastqgz $dirresults/Read2.fastq.gz;`;
   if ($orientation eq "No"){
                    $cmd3 = "(cd $dirresults; $STAR --runThreadN $Nthreads --genomeDir $genome_path --readFilesIn $dirresults/Read1.fastq.gz $dirresults/Read2.fastq.gz --alignIntronMin $alignIntronMin --alignIntronMax $alignIntronMax --outFilterMismatchNmax $outFilterMismatchNmax --readFilesCommand zcat --outSAMstrandField intronMotif --outFileNamePrefix $nb) >& ./out_Star.log 2>&1";
                    system $cmd3;
                    #Info pour les biologistes
                    print STDOUT "STAR command run on cluster without oriented reads : \n\n $cmd1 \n\n ";
                }
                else
                {
                    $cmd4 = "(cd $dirresults; $STAR --runThreadN $Nthreads --genomeDir $genome_path --readFilesIn $dirresults/Read1.fastq.gz $dirresults/Read2.fastq.gz --alignIntronMin $alignIntronMin --alignIntronMax $alignIntronMax --outFilterMismatchNmax $outFilterMismatchNmax --readFilesCommand zcat --outSAMstrandField intronMotif --outFileNamePrefix $nb) >& ./out_Star.log 2>&1";
                    #Info pour les biologistes
                     system $cmd4;
                    print STDOUT "STAR command run on cluster with oriented reads : \n\n $cmd2 \n\n 
                    Instead, you need to run Cufflinks with the library option --library-type options. For example, cufflinks <…> -library-type fr-firststrand should be used for the “standard” dUTP protocol. This option has to be used only for Cufflinks runs and not for STAR runs.\n\n";
                }
}
#Recuperation des fichiers par Galaxy
my $sam = glob("$dirresults/*$nb*.sam");
if (! -e $sam){print STDERR "sam file not found. \n";}else{`cp -a $sam $outputfile`;}
my $log = glob("$dirresults/$nb*Log.final.out");
if (! -e $log){print STDERR "log file not found. \n";}else{`cp -a $log $outputlog`;}
