#!/usr/bin/perl -w

# usage : perl sm_sed.pl 
# 11/02/2014 - Wrapper classique pour le gtraitement de fichiers


# 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 Config::IniFiles;

my $file       = $ARGV[0];
my $motif      = $ARGV[1];
my $substitut  = $ARGV[2];
my $outputfile = $ARGV[3];
my $cmd1 = '';
my $cfg = Config::IniFiles->new( -file => "/path/to/PATH.ini" );

#Récuperer le numero (unique) de l'output afin, si besoin, de créer un répertoire de travail unique dans /work/galaxy/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
my $GALAXYDATA = $cfg->val( 'workPath', 'FILEPATH_DEV' );
`cd $GALAXYDATA/; mkdir $nb/; chmod -R 777 $nb/; cd $nb/;`;
my $dirresults= "$GALAXYDATA".$nb;

#Info pour les biologistes
    print STDOUT "Your tool replace $motif by $substitut in your input file :  $file \n\n ";

#Si besoin, recupération du fichier de configuration avec modification de l extension
`ln -s $file $dirresults/file;`;

#Commande sed
    $cmd1 = "(cd $dirresults; sed -re 's/$motif/$substitut/g' $dirresults/file > $dirresults/out) >& ./out_sed.log 2>&1";
    system $cmd1;
    #Info pour les biologistes
    print STDOUT "Sed command : \n\n $cmd1 \n\n ";


#Recuperation des fichiers par Galaxy
if (! -e "$dirresults/out"){print STDERR "output file not found. \n";}else{`cp -a "$dirresults/out" $outputfile`;}
