# This is a simple template file to use for all wrappers written in perl,
# just copy this file if and adapt i to your needs.
#
# NOTE : this template requires Pod::Usage module

use strict;
use warnings;
use Getopt::Long;
use Pod::Usage;
use File::Temp qw/ tempdir tempfile /;
use File::Basename;

my $KMER_PIPELINE = '/usr/local/bioinfo/src/NIKS/current/kmerPipeline/src/kmerPipeline.sh';
my $KMER_PIPELINE_INDEL = '/usr/local/bioinfo/src/NIKS/current/kmerPipeline/src/kmerPipelineInDels.sh';
my $JELLYFISH = '/usr/local/bioinfo/bin/jellyfish';

# set path to include jellyfish
# this is done already by admin, but it does not work so I have to do it
my $path = $ENV{PATH} || '';
$path = join( ':', $path, dirname($JELLYFISH) );
$ENV{PATH} = $path;


sub is_gzip($){
    my $path = shift;
    my $type = `file $path | cut -f 1 -d ',' | cut -d':' -f 2`;
    chomp($type);
    if ($type =~ /gzip/){
        return "true";
    }
    return undef;
}


main :
{
    my %options;
    Getopt::Long::Configure( 'no_ignorecase', 'bundling' );
    GetOptions (\%options,
        'h|?|help',
        'fastqa1=s@',
        'fastqa2=s@',
        'fastqb1=s@',
        'fastqb2=s@',
        'insert-size=i',
        'output-fasta-a=s',
        'output-fasta-b=s',
        'output-csv=s',
        'pipeline-type=s',
        
        # those parameters will not be set for the moment by the xml file
        #'kmer-size=i',
        #'lmer-size=i',
        #'maxcutoff=i',
        #'min-size=i',
        #'tolerance=i',

        # specific to $KMER_PIPELINE
        #'highboundary=i'
    )  or  pod2usage( -verbose => 1 , noperldoc => 1) ;
    pod2usage( -verbose => 1 , noperldoc => 1) if (exists $options{'h'}) ;
    
    foreach my $param ( qw/ fastqa1 fastqb1 pipeline-type / ) {
        pod2usage( -msg => "$param is required", -verbose => 1 , noperldoc => 1) unless (exists $options{$param}) ;
    }
    
    my @fastqa1 = @{$options{'fastqa1'}} ;
    my @fastqa2 = $options{'fastqa2'} ?  @{$options{'fastqa2'}} : ();
    my @fastqb1 = @{$options{'fastqb1'}};
    my @fastqb2 = $options{'fastqb2'} ?  @{$options{'fastqb2'}} : ();
    my @fastqa1_new_loc = ();
    my @fastqa2_new_loc = ();
    my @fastqb1_new_loc = ();
    my @fastqb2_new_loc = ();
    my $insert_size = $options{'insert-size'} ;
    my $output_fasta_a = $options{'output-fasta-a'};
    my $output_fasta_b = $options{'output-fasta-b'};
    my $output_csv = $options{'output-csv'};
    my $pipeline = $options{'pipeline-type'};
    
    #my $kmer_size = $options{'kmer-size'} || 31;
    #my $lmer_size = $options{'lmer-size'} || 25;
    #my $maxcutoff = $options{'maxcutoff'} || 100;
    #my $min_size = $options{'min-size'} || 21;
    #my $tolerance = $options{'tolerance'} || 10 ;
    #my $highboundary = $options{'highboundary'} || 10000;
    
    unless ($pipeline =~ /^KMER|KMER_INDEL$/i) {
        die "--pipeline-type must be in 'KMER' or 'KMER_INDEL']";
    }
    
    # Change LD_IBRARY_PATH
    my $LD_LIB = $ENV{LD_LIBRARY_PATH} ? ":$ENV{LD_LIBRARY_PATH}" : '';
    $ENV{LD_LIBRARY_PATH} = '/usr/local/bioinfo/src/Jellifish/current/lib/' . $LD_LIB ;
    
    # repertoire de travail dans /work/galaxy***/tmp
    my $path = dirname(dirname(dirname(dirname($fastqa1[1]))));
    my $workdir = tempdir( 'workdir_niks_XXXXXXX', DIR => "$path/tmp" , CLEANUP => 1);
	chmod( 0755, $workdir);
    #my ($fh, $log) = tempfile( 'wrapper_niks_XXXXXX', SUFFIX => '.log');
    
    my $fastq_location_temp = tempdir( 'fastq_location_XXXXXXX', DIR => $workdir , CLEANUP => 1);

    #copy all fastq files and check ther format. change the name accordingly
    foreach my $f (@fastqa1){
        my $path = $fastq_location_temp . '/' . basename($f) ;
        `cp $f $path`;
        
        if ( is_gzip($path) ) {
            #move with appropriate name
            if ($path !~ /\.gz$/ ){
                `mv $path $path.gz` ;
                $path = "$path.gz";
            }
        }
        else {
            `gzip $path`;
            $path = "$path.gz";
        }
        push (@fastqa1_new_loc, $path )
    }
    foreach my $f (@fastqb1){
        my $path = $fastq_location_temp . '/' . basename($f) ;
        `cp $f $path`;
        
        if ( is_gzip($path) ) {
            #move with appropriate name
            if ($path !~ /\.gz$/ ){
                `mv $path $path.gz` ;
                $path = "$path.gz";
            }
        }
        else {
            `gzip $path`;
            $path = "$path.gz";
        }
        push (@fastqb1_new_loc, $path )
    }
    
    # copier le script qu'il faut en fonction de $pipeline
    my $main_script_path = $workdir . '/';
    
    if( $pipeline =~ /^KMER_INDEL$/){
        system( "cp $KMER_PIPELINE_INDEL $workdir/" );
        $main_script_path .= basename($KMER_PIPELINE_INDEL);
    }
    else {
        system( "cp $KMER_PIPELINE $workdir/" );
        $main_script_path .= basename($KMER_PIPELINE);
    }
    
    # editer le script pour modifier les bonnes valeurs
    # TODO : gerer les echantillons pairés
    
    my $files_fastqa1 = '"' . join (" " , @fastqa1) . '"';
    my $files_fastqb1 = '"' . join (" " , @fastqb1) . '"';

    my $cmd1 =  "sed -i -e 's,^FASTQA1=.*,FASTQA1=$files_fastqa1,'  $main_script_path";
    my $cmd2 =  "sed -i -e 's,^FASTQB1=.*,FASTQA1=$files_fastqb1,'  $main_script_path" ;
    my $cmd3 =  "sed -i -e 's,^FASTQINSERT=.*,FASTQINSERT=$insert_size,'  $main_script_path" ;

    system( $cmd1 );
    system( $cmd2 );
    system( $cmd3 )  if ($insert_size);
    
    # lancer le script
    system( "cd $workdir; /bin/bash $main_script_path" );
    
    # copier les résultats et le log
    system( "cp $workdir/A_candidates_ext.fa  $output_fasta_a" );
    system( "cp $workdir/B_candidates_ext.fa  $output_fasta_b" );
    system( "cp $workdir/A_summaryBOTH.csv  $output_csv" );
}

=head1 NAME

wrapper_niks.pl

=head1 SYNOPSIS

wrapper_niks.pl [OPTIONS]

=head1 OPTIONS

    -h,--help
        Help
    
    --fastqa1 FASTQA1
        Pair 1 fastq gz for sample A. Use multiple --fastqa1 for multiple input file
    
    --fastqa2 FASTQA2
        Pair 2 fastq gz for sample A
        
    --fastqb1 FASTQB1
        Pair 1 fastq gz for sample B. Use multiple --fastqa1 for multiple input file
    
    --fastqb2 FASTQB2
        Pair 2 fastq gz for sample B
        
    --insert-size INT
        Insert size 
        
    --output-fasta-a PATH
        Prefix for generated fasta file A
    
    --output-fasta-b PATH
        Prefix for generated fasta file B

    --output-csv PATH
        One spread sheet with some stats
    
    --pipeline-type TYPE
        One of KMER or KMER_INDEL.
        
    --kmer-size INT
        k-mer size [31]
        
    --lmer-size INT
        l-mer for seed generation [25]
        
    --maxcutoff INT
        maximum value for a cutoff from the histogram [100]
        
    --min-size INT
        minimum number of kmers to make up a seed (minlength= MINSIZE+KMERSIZE-1) [21]
        
    --tolerance INT
        tolerance in seed pairing [10]

    --highboundary INT
        specific to KMER_PIPELINE [10000]

=cut

