#!/usr/bin/env nextflow
nextflow.enable.dsl=2

/*
========================================================================================
                         ega-submission-via-portal
========================================================================================
 https://git.ecdf.ed.ac.uk/igmmbioinformatics/ega-submission-via-portal
----------------------------------------------------------------------------------------
*/

include { EGA_ENCRYPT } from './modules/local/ega/encrypt'
include { EGA_COLLECTRUNCSVS } from './modules/local/ega/collectruncsvs'
include { EGA_UPLOAD } from './modules/local/ega/upload'

def helpMessage = """
    Usage:

    The typical command for running the pipeline is as follows:

    nextflow run https://git.ecdf.ed.ac.uk/igmmbioinformatics/ega-submission-via-portal
        --samples samples.csv
        --reads '*_R{1,2}.fastq.gz'
        -profile conda


    Mandatory arguments:
      --samples [file]              Path to samples CSV file
      --reads [file]                Path to input data (must be surrounded with quotes, e.g. '*_R[1,2].fastq.gz]')
      -profile [str]                Configuration profile to use. Can use multiple (comma separated)
                                    Available: conda, stubs

    Other options:
      --outdir [file]               The output directory where the results will be saved
      --ega_user [str]              EGA upload box account (e.g. ega-box-1234)
      --egapass [str]               Absolute path to a file containing password for EGA upload box account, must be specified if --ega-user is specified
      -name [str]                   Name for the pipeline run. If not specified, Nextflow will automatically generate a random mnemonic
""".stripIndent()


workflow {
    if (params.help) {
        log.info(helpMessage)
        exit 0
    }

    ch_read_files = Channel
        .fromFilePairs(params.reads, size: 2)
        .ifEmpty({ exit 1, "Cannot find any reads matching: ${params.reads}\nNB: Path needs to be enclosed in quotes!" })

    ch_egapass = params.egapass && file(params.egapass).exists() ? Channel.fromPath(params.egapass).collect() : Channel.value('')

    EGA_ENCRYPT(ch_read_files)
    EGA_COLLECTRUNCSVS(EGA_ENCRYPT.out.csv.map({sample, csv -> csv}).collect())
    EGA_UPLOAD(EGA_ENCRYPT.out.all, ch_egapass)
}