#! /usr/bin/env nextflow

def helpMessage() {
  log.info """
        Usage:
        The typical command for running the pipeline is as follows:
        nextflow run main.nf --sra_run SRR1234567 "blastDatabaseDirectory" --dbName "blastPrefixName"

        Mandatory arguments:
         --sra_run                     Accession for the SRA run to be analyzed (SRR1234567 is just an example!)
         --REnzyme                     Restriction enzyme used in HiC library preparation

       Optional arguments:
        --data_dir                     Directory to store large data files (SRA, FASTQ)
        --help                         This usage statement.
        --reference                    The reference genome in FASTA format. It is used to provide repetitive sequences to which the HiC data will be aligned. It is best to use the same species that was sequenced by HiC but default Oryza can provide a rough estimate (TODO make this a mix of species?).
        --teref_size                   The number of TEs per family to be included in the "artificial chromozomes" (default = 3; is used to set the -max_target_seqs parameter of tblastn)
        """
}

// Show help message
if (params.help) {
    println("")
    helpMessage()
    println("")
    exit 0
}

// Check mandatory arguments
if (!params.sra_run) {
    println("Mandatory parameter --sra_run not specified on command line. Exiting.")
    exit 0
}
if (!params.REnzyme) {
    println("Mandatory parameter --REnzyme not specified on command line. Exiting.")
    exit 0
}
// Generated reference genome base name
ref_dir = file(params.reference).baseName

// Path to Diachromatic.jar
diachromatic_path = "/home/lexa/hic/diachromatic/target"

hic_truncated_name = "${params.sra_run}-HiC.truncated_R"
diachromatic_name = "${params.sra_run}_diachromatic_truncated_paired_ref"

println "\nI will run TE-g-nester on $params.reference"

process runTEgnester {

    output:
    val(file("$params.data_dir/$ref_dir")) into nester_output_ch

    script:
    """
    [ ! -d "$params.data_dir/$ref_dir" ] && mkdir $params.data_dir/$ref_dir
    nested-nester -d ${params.data_dir}/${ref_dir} -n 3 ${params.data_dir}/${params.reference}
    """
}

process generateBowtieIndex {
    //publishDir "${params.data_dir}", mode: 'symlink', enabled: true

    input:
    path refdir from "${params.data_dir}/${params.reference}"

    output:
    //path "ref_${ref_dir}*"
    val "${params.data_dir}/ref_${ref_dir}" into ref_index_ch

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

println "\nI will download ${params.sra_run} to ${params.data_dir}\n"

process prefetchSRA {

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

    storeDir "${params.data_dir}"

    output:

    val "${params.data_dir}/${params.sra_run}" into prefetch_ch

    script:
    """
    prefetch ${params.sra_run} -O ${params.data_dir}/${params.sra_run} --max-size u
    """
}

process convertToFastq {

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

    input:
    path prefetch_dir from prefetch_ch

    output:
    val "${params.data_dir}/${params.sra_run}/${params.sra_run}_1.fastq" into fastq1_ch
    val "${params.data_dir}/${params.sra_run}/${params.sra_run}_2.fastq" into fastq2_ch

    script:
    """
    cd ${prefetch_dir}
    fasterq-dump -f ${params.sra_run}
    """
}

fastq1_ch.subscribe{println("$it")}
fastq1_ch.subscribe{println("$it")}

process truncateOnRESite {

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

    input:
    path fastq1 from fastq1_ch
    path fastq2 from fastq2_ch

    output:
    val "${params.data_dir}/${hic_truncated_name}1.fastq.gz" into tfastq1_ch
    val "${params.data_dir}/${hic_truncated_name}2.fastq.gz" into tfastq2_ch

    script:
    """
    /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java -jar ${diachromatic_path}/Diachromatic.jar truncate -q ${fastq1} -r ${fastq2} -e $params.REnzyme -x ${params.sra_run}-HiC -o $params.data_dir/.
    """
}

tfastq1_ch.subscribe{println("$it")}
tfastq2_ch.subscribe{println("$it")}

process alignReads {

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

    input:
    path tfastq1 from tfastq1_ch
    path tfastq2 from tfastq2_ch
    val ref_index from ref_index_ch

    output:
    val "${params.data_dir}/${diachromatic_name}.bam" into bam_ch

    script:
    """
    bowtie2 -x ${ref_index} --threads 5 -1 ${tfastq1} -2 ${tfastq2} | samtools view -@ 6 -b -S > ${params.data_dir}/${diachromatic_name}.bam
    """
}
