#!/bin/bash

# Preprocessing - RNA-Seq PE
#
# Requires FastQC, FastP, multiQC
#
qsub -l walltime=2:0:0 -q default -l select=1:ncpus=6:mem=30gb:scratch_local=50gb -I
#

############################################################################################
### Variables
USERNAME="bartonv"
THREADS=$PBS_NUM_PPN # Number of threads to use
INPUT_DIR=/storage/brno2/home/${USERNAME}/RNASeq/data/raw
OUTPUT_DIR=/storage/brno2/home/${USERNAME}/RNASeq/data/preprocessed
REPORT_DIR=/storage/brno2/home/${USERNAME}/RNASeq/results/fastp


mkdir -p RNASeq/data/preprocessed
mkdir -p RNASeq/results/fastp

### load modules
module add fastqc

module add python27-modules-gcc # multiqc

module add fastp



############################################################################################
### Preprocess and qc
mkdir -p RNASeq/results/fastp

for file in $INPUT_DIR/*_1.fastq.gz; do
	file_F=$(basename $file)
	file_R=${file_F%"_1.fastq.gz"}_2.fastq.gz
	
	fastp \
		-i $INPUT_DIR/$file_F \
		-o $OUTPUT_DIR/$(basename $file_F) \
		-I $INPUT_DIR/${file_R} \
		-O $OUTPUT_DIR/$(basename $file_R) \
		--thread $THREADS \
		--detect_adapter_for_pe \
		--trim_poly_g \
		--cut_front \
		--cut_tail \
		--cut_mean_quality 30 \
		--average_qual 30 \
		--length_required 50 \
		--json $REPORT_DIR/${file_F%"_1.fastq.gz"}.fastp.json \
		--html $REPORT_DIR/${file_F%"_1.fastq.gz"}.fastp.html
done


mkdir -p RNASeq/results/qc/fastqc/preprocessed

#fastqc on preprocessed reads
fastqc --outdir RNASeq/results/qc/fastqc/preprocessed --format fastq --threads $THREADS $OUTPUT_DIR/*.fastq.gz

#multiqc on fastqc files
multiqc -o  RNASeq/results/qc/fastqc/preprocessed  RNASeq/results/qc/fastqc/preprocessed

#mutliqc on fastp logs
multiqc -o $REPORT_DIR $REPORT_DIR
