#!/bin/sh

DIR="$( cd "$( dirname "$0" )" && pwd )"
source $DIR/rtg-galaxy.cfg

# Temporary storage for STDERR
# Temporary storage for mapping output
TMP_STDERR=$(mktemp) || exit 1

#echo "$(date) START $@" >>~/galaxy-rtg-wrapper.log

paired=$1
shift
outputfile=$1
shift
if [ $paired == "paired" ]; then
    outputfile2=$1
fi
shift
outputdir=$1
shift

# Run the program, send STDERR to temporary file
tmpout=$outputdir/tmpout$$
$rtg "$@" -o $tmpout --legacy-cigars 2> $TMP_STDERR

#check program's exit code
if (( $? ));  then
    #echo "$(date) FAIL $@" >>~/galaxy-rtg-wrapper.log
    #cat $TMP_STDERR >>~/galaxy-rtg-wrapper.log
    #Program failed, send STDERR to real STDERR
    cat $TMP_STDERR >&2
    rm $TMP_STDERR
    rm -rf $tmpout
    exit 1
fi

if [ -f $tmpout/mated.sam.gz ]; then
    mv $tmpout/mated.sam.gz $outputfile
    [ "$outputfile2" ] && mv $tmpout/unmated.sam.gz $outputfile2
else
    mv $tmpout/alignments.sam.gz $outputfile
fi

#echo "$(date) DONE $@" >>~/galaxy-rtg-wrapper.log

#Program succeeded, delete STDERR file
rm $TMP_STDERR
rm -rf $tmpout
exit 0
