#!/bin/bash
set -e

inputFile=$1
outputFile=$2
outputDir=$3
database=$4
limit_reads=$5
limit_ratio=$6
selection=$7
germline=$8

dir="$(cd "$(dirname "$0")" && pwd)"
mkdir $outputDir

unzip $dir/browser.zip -d $outputDir/ > $outputDir/unziplog.log

mkdir $outputDir/data

if [[ "$database" == "download" ]] ; then
	echo "Downloading up to date database from IMGT..."
	mkdir $outputDir/tmp
	mkdir $outputDir/tmp/germline
	cp $dir/germline/get-germline $outputDir/tmp/germline
	cp $dir/germline/split-from-imgt.py $outputDir/tmp/germline
	cp $dir/vidjil $outputDir/tmp
	cd $outputDir/tmp/germline
	./get-germline 2>&1
	cd $outputDir/tmp
else
	cd $dir
fi


inputFiles=$(echo "$inputFile" | tr "| " "\n")
files_for_config=""
last_file=""
for id_file in $inputFiles
do
	tmp=($(echo "${id_file}" | tr ";" "\n"))
	id=${tmp[0]}
	file=${tmp[1]}
	
	./vidjil -G germline/$germline -y all -r ${limit_reads} -% ${limit_ratio} -b $id -o $outputDir/data $file
	
	if [[ "$files_for_config" != "" ]] ; then
		files_for_config="${files_for_config},"
	fi
	files_for_config="${files_for_config}'${id}.vidjil'"
	last_file="${id}.vidjil"
done

echo "<html><center><h1><a href='index.html'>Click here for the results</a></h1>Tip: Open it in a new tab (middle mouse button or right mouse button -> 'open in new tab' on the link above)</center></html>" > $outputFile

echo -e \
"var config = {\n" \
"    'file_menu' : {\n" \
"        'path' : 'data/',\n" \
"        'file' : [\n" \
"            ${files_for_config}\n" \
"        ]\n" \
"    },\n" \
"    'autoload' : 'data/${last_file}'\n" \
"}" > $outputDir/js/conf.js;
