#!/bin/sh

### Galaxy Wrapper for BAMqc ###

alignment_files=""
refgene=""
attrID=""
rRNA=""
outputHTML=""
stranded=""
mapq="30"
lowBound="-250"
upperBound="250"
stepSize="5"
labels=""
cores="1"

ARGS=$(getopt -o "r:f:R:o:s:p:q:" -- "$@")

if [ $? -ne 0 ]; then
    echo "Invalid command-line parameters. Do not use this script outside of Galaxy" >&2
    exit 1
fi

eval set -- "$ARGS"

while [ $# -gt 0 ]; do
  case "$1" in
      -r)
	  refgene="$2"
	  shift 2
	  ;;
      -f)
	  attrID="$2"	
	  shift 2
	  ;;
      -R)
	  rRNA="$2"
	  shift 2
	  ;;
      -o)
	  outputHTML=$2
	  shift 2
	  ;;
      -s)
	  stranded=$2
	  shift 2
	  ;;
      -q)
	  mapq=$2
	  shift 2
	  ;;

      -p)
	  cores=$2
	  shift 2
	  ;;
      --)
	  shift
	  break
	  ;;
  esac
done

if [ "$cores" -gt 10 ];then
    cores="10"
fi

outputDir=`echo $outputHTML | sed 's/\.dat$/_files/'`
if [ ! -d "$outputDir" ]; then
    mkdir $outputDir
fi

touch bamqc.log

while [ "$#" -ne 0 ];
do
  FILE="$1"
  LABEL=`echo $2 | sed 's/ /-/g; s/\[//; s/\]//;'`
  shift 2
  QNAME_SORTED=`samtools view -H ${FILE} | grep "SO:queryname"`
  if [ $? -ne 0 ]; then
      BASE=`basename ${FILE} \.dat`
      echo "Sorting BAM file (${LABEL}." >>samtools.log
      samtools sort -@ 5 -n ${FILE} ${BASE} 2>>samtools.log
      if [ $? -ne 0 ]; then
	  echo "Error with samtools sorting for BAM file (${LABEL})." >&2
	  cat samtools.log >&2
	  exit 1
      fi
      echo "BAM file (${LABEL}) was re-sorted by query name." >>bamqc.log
      FILELIST="$FILELIST ${BASE}.bam"
  else
      FILELIST="$FILELIST $FILE"
  fi
  LABELLIST="$LABELLIST $LABEL"
done

CMD="ezBAMQC -i $FILELIST -l $LABELLIST -f $attrID -r $refgene -o Galaxy_BAMqc_output --stranded $stranded -q $mapq --rRNA $rRNA -t $cores"

echo "BAMqc command: $CMD" >> bamqc.log
echo >> bamqc.log

$CMD 2>> bamqc.log

if [ $? -ne 0 ]; then
    echo "BAMqc ran with errors" >&2
    cat bamqc.log >&2
    exit 1
fi

sed -i "s/\.\.\/Galaxy_BAMqc_output\///g;" Galaxy_BAMqc_output/bamqc_output.html

cp -r Galaxy_BAMqc_output/data "$outputDir"
cp -r Galaxy_BAMqc_output/figs "$outputDir"
cp Galaxy_BAMqc_output/bamqc_output.html "$outputHTML"

if [ $? -ne 0 ]; then
    echo "Copying BAMqc results failed" >&2
fi

echo "BAMqc results copied to $outputDir" >>bamqc.log
