#!/usr/bin/env nextflow

// Generated reference genome base name
ref_dir = file(params.reference).baseName
save_enabled = params.save_intermediate

use_docker_container = params.singularity_use_docker_container

diachromatic_name = "${params.sra_run}_diachromatic_truncated_paired_ref"

process BOWTIE2_BUILD {

    publishDir "${params.data_dir}", mode: 'copy', enabled: save_enabled

    if (workflow.containerEngine == 'singularity' && !use_docker_container) {
        container "https://depot.galaxyproject.org/singularity/bowtie2:2.4.4--py39hbb4e92a_0"
    } else {
        container "quay.io/biocontainers/bowtie2:2.4.4--py39hbb4e92a_0"
    }

    input:
    path refdir

    output:
    path 'bowtie2', emit: bowtie2_index_ch

    script:
    """
    mkdir bowtie2
    bowtie2-build --threads 4 ${refdir} bowtie2/${ref_dir}
    """
}

process ALIGN_READS {

    publishDir "${params.data_dir}", mode: 'copy', enabled: save_enabled

    if (workflow.containerEngine == 'singularity' && !use_docker_container) {
        container "https://depot.galaxyproject.org/singularity/mulled-v2-c742dccc9d8fabfcff2af0d8d6799dbc711366cf:b6524911af823c7c52518f6c886b86916d062940-0"
    } else {
        container "quay.io/biocontainers/mulled-v2-c742dccc9d8fabfcff2af0d8d6799dbc711366cf:b6524911af823c7c52518f6c886b86916d062940-0"
    }

    input:
    tuple val(sra_id), path(tfastq)
    path bowtie2_index

    output:
    path "${diachromatic_name}.bam", emit: bam_ch

    script:
    index = ( params.skip_bow_index ? params.input_bow_index : "${bowtie2_index}/${ref_dir}" )
    """
    bowtie2 -x ${index} --threads 5 -1 ${tfastq[0]} -2 ${tfastq[1]} | samtools view -@ 6 -bhS -o ${diachromatic_name}.bam -
    """
}
