#!/bin/bash

if [ "$#" == "0" ]; then
echo "Error: No arguments" >&2; exit 1;
fi

if [ "$#" == "1" ]; then
        if [ "$1" == "-v" ] || [ "$1" == "--version" ]; then
                docker run docker-tellread cat /tellysis/tellread/version.txt; exit 1;
        fi
fi

while (( "$#" )); do
  case "$1" in
    -i1|--i1)
      i1=$2
      shift 2
      ;;
    -i2|--i2)
      i2=$2
      shift 2
      ;;
    -r1|--r1)
      r1=$2
      shift 2
      ;;
    -r2|--r2)
      r2=$2
      shift 2
      ;;
    -o|--output)
      output_path=$2
      shift 2
      ;;
    -m|--machine)
      m=$2
      shift 2
      ;;
    -f|--reference)
      ref_path=$2
      shift 2
      ;;
    -s|--samples)
      samples=$2
      shift 2
      ;;
    -g|--genomes)
      genomes=$2
      shift 2
      ;;
    -*|--*=|*) # unsupported flags
      echo "Error: Unsupported flag $1" >&2
      exit 1
      ;;
  esac
done

mkdir -p $output_path

#Absence of I2 means single sample analysis
#No need to worry about I2 reverse compliment
#Sample name & machine type are merely place holders
r2_fq='';
i2_fq='';
#cp $i1 $output_path/I1.fastq.gz
#cp $r1 $output_path/R1.fastq.gz
if [ "$i2" != '' ]; then
	#cp $i2 $output_path/I2.fastq.gz
	i2_fq="-i_2 $output_path/I2.fastq.gz";
	m_opt="-m $m";
else
	m_opt="-m HiSeq";
	samples="T500";
fi
if [ "$r2" != '' ]; then
	#cp $r2 $output_path/R2.fastq.gz
	r2_fq="-r_2 $output_path/R2.fastq.gz";
fi

cmd_opt="-i_1 $output_path/I1.fastq.gz $i2_fq -r_1 $output_path/R1.fastq.gz $r2_fq $m_opt -o $output_path -s $samples -g $genomes"

echo $cmd_opt

mkdir -p $output_path
docker run \
	-v $output_path:$output_path \
	-v $ref_path:/tellysis/genomes   \
	docker-tellread  \
	bash -c "'/tellysis/tellread/StartTellReadPipelineSeq $cmd_opt 2>&1 | tee $output_path/$(basename $output_path).log'"

