#!/bin/bash
# split sequencing run into a new folder
#
# 1 - seqrun path, e.g. /cs/nextseq/181231_NS500183_0503_AHGFF2BGX9
# 2 - debug, if "1", will bcl2fastq only some tiles to speed things up
# 3 - number of threads to split with, default=8
# 4 - project name, default="4tU_deg"
# 5 - barcodes_tab, default is all 5 RNA barcodes:
#     F1	ATCTCGTA	ATTAGACG
#     F2	ATCTCGTA	ATAGAGAG
#     ...

# setup environment
source /cs/bd/tools/4tU_scripts/v3/set_rnadb_env
set -e
BCL2FQ="/usr/local/bcl2fastq/2.20.0/bin/bcl2fastq";
BCL_ARGS="-l WARNING --minimum-trimmed-read-length 5 --no-lane-splitting --mask-short-adapter-reads 5"
FQC_ARGS="-q -t 6"
B2Q_REP="bcl2fq-report"
FQ_REP="fastqc-report"
QC_REP="qc-report"

# parse inputs
path=$1;
debug=${2:-0};
b2f_p=${3:-8};
proj=${4:-"4tU_deg"};
bc_file=${5:-"$SRC/external_barcodes.tab"};

if [ "$debug" -eq "1" ]; then
   BCL_ARGS=$BCL_ARGS" --tiles [0-9][0-9][0-9]5";
   echoerr "debug mode!"
fi

# parse seqrun name
sr=${path##*/};
IFS=_ read -r date machine run kit <<<"$sr"
if [[ ! "$date" =~ ^[0-9]+$ ]]; then echo "date was not parsed properly"; exit 99; fi
if [[ ! "$machine" =~ ^N[BS][0-9]+$ ]]; then echo "machine name was not parsed properly"; exit 99; fi
if [[ ! "$run" =~ ^[0-9]+$ ]]; then echo "run number was not parsed properly"; exit 99; fi
if [[ ! "$kit" =~ ^[A-Z0-9]{10}$ ]]; then echo "kit id was not parsed properly"; exit 99; fi
sid=$date"-"$kit;
stats_dir=$DATA_ROOT/$proj/$STATS_DIR/$sid
lib_fastq_dir=$DATA_ROOT/$proj/$LIB_FASTQ_DIR
tmp_dir=$DATA_ROOT/$proj/$TMP_DIR/$sid
mkdir -p $tmp_dir $lib_fastq_dir $stats_dir

echoerr "processing $path (date=$date, machine=$machine, run=$run, kit=$kit)"

# build temporary directory tree
fastq_dir=$tmp_dir/fastq
fqc_stats_dir=$tmp_dir/fqc
tmp_stats=$tmp_dir/stats
b2q_stats_dir=$tmp_dir/b2q
mkdir -p $fastq_dir $fqc_stats_dir $b2q_stats_dir $tmp_stats

www_output=$WWW_ROOT/$proj/$WWW_SEQRUN_DIR/$sid
url_root=$URL_ROOT/$proj/$WWW_SEQRUN_DIR/$sid
b2q_report_dir=$www_output/$B2Q_REP
fqc_report_dir=$www_output/$FQ_REP
qc_dir=$www_output/$QC_REP
rm -Rf $www_output
mkdir -p $b2q_report_dir $fqc_report_dir $qc_dir

# setup local environment in tmp directory for bcl2fastq
cd $tmp_dir
ln -sf $path/* .
cat $SRC/illumina_sample_sheet_header <(cat $bc_file | grep -v "^#" | nl -s $'\t' | tr -d " " | tr "\t" ",") > SampleSheet.csv

# execute and clear
echoerr "running bcl2fastq..."
$BCL2FQ -o $fastq_dir -p 8 $BCL_ARGS
rm $fastq_dir/*Undetermined_*.fastq.gz

# move bcl2fastq outputs
mv  $fastq_dir/Reports/html/* $b2q_report_dir/
mv  $fastq_dir/Stats/* $b2q_stats_dir
rm -Rf $fastq_dir/Reports $fastq_dir/Stats $fastq_dir/Stats.json

# collect statistics from bcl2fastq output
$SRC/collect_bcl2fq $b2q_stats_dir \
                    " sed '/###/q' | head -n -2 " \
                    "DemuxSummaryF1L?.txt" \
                    " sed '/###/q' | head -n -2 | awk 'NR>2' " |
gzip > $tmp_stats/tile_percent.bcl.tab.gz

cat <(printf '%s\t%s\t%s\n' "barcodes" "count" "lane") \
    <($SRC/collect_bcl2fq $b2q_stats_dir " grep + | awk -v OFS='\t' -v lane=\$lane '{print \$0,lane;}' " "DemuxSummaryF1L?.txt") |
gzip > $tmp_stats/unknown_bcs.bcl.tab.gz

$SRC/collect_bcl2fq $b2q_stats_dir \
                    " awk -v OFS='\t' -v l=\$lane -v head="Lane" '{print \$0,(NR==1)?head:l;}' "\
                    "FastqSummaryF1L?.txt" \
                    " awk -v OFS='\t' -v l=\$lane 'NR>1 {print \$0,l}' " |
gzip > $tmp_stats/tile_counts.bcl.tab.gz

cat $b2q_stats_dir/DemultiplexingStats.xml | python $SRC/b2fqxml2tab.py |
gzip > $tmp_stats/lane_bc_cnt.bcl.tab.gz

rm -Rf $b2q_stats_dir

# generate fastqc reports
echoerr "running fastqc..."
fastqc $fastq_dir/*.fastq.gz -o $fqc_stats_dir $FQC_ARGS 2> /dev/null

# collect stat tables, and move html reports
python $SRC/collect_fastqc_data.py $fqc_stats_dir/*.zip -op $tmp_stats/
mv $fqc_stats_dir/*.html $fqc_report_dir/
rm -Rf $fqc_stats_dir

# copy stats to www, and generate qc plots in appropriate place
pushd $tmp_stats && tar -cvzf $www_output/stats.tar.gz . && popd
python $SRC/plot_seqrun_stats.py  -s $tmp_stats -o $qc_dir -t "Sequencing Run $kit on $date"

#chmod to have web access
chmod -R 777 $www_output

# move stats to general pool
mv $tmp_stats/* $stats_dir/

#move fastq to general pool and split inner barcodes
for f1 in $fastq_dir/*R1*.fastq.gz; do
  name=${f1##*/};
  name=${name%_*};
  sample=${name%%_*};
  f2=${f1/R1/R2};
  mv $f1 $lib_fastq_dir/$sid.$sample.R1.fq.gz
  mv $f2 $lib_fastq_dir/$sid.$sample.R2.fq.gz
  $SRC/split_library $lib_fastq_dir/$sid.$sample
done

# and delete tmp files
cd $DATA_ROOT
rm -Rf $tmp_dir

echoerr "fastq files available in $lib_fastq_dir/$sid*"
echoerr "statistics are available in $stats_dir/$sid/*"
echoerr "web accessible stats and figures are found in: "
echoerr "  "$URL_ROOT/$proj/$WWW_SEQRUN_DIR/$sid/$B2Q_REP
echoerr "  "$URL_ROOT/$proj/$WWW_SEQRUN_DIR/$sid/$FQ_REP
echoerr "  "$URL_ROOT/$proj/$WWW_SEQRUN_DIR/$sid/$QC_REP/report.html #TODO make the report name a variable..
