// main script name
manifest {
    author = 'Robert A. Petit III'
    name = 'bactopia'
    homePage = 'https://github.com/bactopia/bactopia'
    description = 'An extensive workflow for processing Illumina sequencing of bacterial genomes.'
    mainScript = 'main.nf'
    version = '3.0.0'
    nextflowVersion = '>=21.10'
}

// Includes
bactopia_cache = System.getenv("BACTOPIA_CACHEDIR") ? "${BACTOPIA_CACHEDIR}" : "${HOME}/.bactopia"
includeConfig "conf/params.config"
includeConfig "conf/workflows.config"
if (params.workflows.containsKey(params.wf)) {
    if (params.workflows[params.wf].containsKey("is_workflow")) {
        // Running as main workflow (e.g. bactopia/staphopia)
        includeConfig "conf/params/bactopia.config"

        params.workflows[params.wf]['includes'].each { it ->
            if (params.workflows[it].containsKey("modules")) {
                // Subworkflow which includes multiple modules
                params.workflows[it]['modules'].each { module ->
                    includeConfig "${params.workflows[module].path}/params.config"
                }
            } else {
                // Module
                includeConfig "${params.workflows[it].path}/params.config"
            }
        }

        if (params.containsKey("ask_merlin")) {
            if (params.ask_merlin) {
                params.workflows['merlin']['modules'].each { module -> 
                    includeConfig "${params.workflows[module].path}/params.config"
                }
            }
        }
        if (params.wf == "bactopia" || params.wf == "staphopia") {
            if (params.use_bakta) {
                params.workflows['bakta']['modules'].each { module -> 
                    includeConfig "${params.workflows[module].path}/params.config"
                }
            } else {
                includeConfig "${params.workflows['prokka'].path}/params.config"
            }
        }

        if (params.wf == "cleanyerreads") {
            includeConfig "conf/params/clean-yer-reads.config"
        } else if (params.wf == "teton") {
            includeConfig "conf/params/teton.config"
        } 
    } else {
        // Running as bactopia tool
        includeConfig "conf/params/bactopia-tools.config"
        if (params.workflows[params.wf].containsKey("use_local")) {
            includeConfig "conf/params/local/${params.workflows[params.wf].use_local}.config"
        }

        if (params.workflows[params.wf].containsKey("modules")) {
            // Subworkflow which includes multiple modules
            params.workflows[params.wf]['modules'].each { module ->
                includeConfig "${params.workflows[module].path}/params.config"
            }
        }
        if (params.workflows[params.wf].containsKey("path")) {
            // Module
            includeConfig "${params.workflows[params.wf].path}/params.config"
        }
    }
} else {
    // Include main bactopia params
    includeConfig "conf/params/bactopia.config"
}

if (params.is_ci) {
    includeConfig "conf/tests.config"
}
includeConfig "conf/outputs.config"

// Set up containers
run_timestamp = new java.util.Date().format('yyyyMMdd-HHmmss')
rundir = "${params.wf}-${run_timestamp}"
if (params.is_ci) {
    rundir = "${params.wf}"
}
singularity_cache = System.getenv("NXF_SINGULARITY_CACHEDIR") ? "${NXF_SINGULARITY_CACHEDIR}" : "${params.singularity_cache}"
includeConfig "conf/profiles.config"

if (params.nfconfig) {
    includeConfig check_path(params.nfconfig)
}

if (!params.help || !params.help || !params.list_wfs) {
    infodir = "${params.outdir}/bactopia-runs/${rundir}/nf-reports"

    // Reporting configuration
    timeline {
        enabled = true
        overwrite = true
        file = "${infodir}/${params.wf}-timeline.html"
    }

    report {
        enabled = true
        overwrite = true
        file = "${infodir}/${params.wf}-report.html"
    }

    trace {
        enabled = true
        overwrite = true
        file = "${infodir}/${params.wf}-trace.txt"
        fields = 'task_id,hash,native_id,process,tag,name,status,exit,module,container,cpus,time,disk,memory,attempt,start,complete,duration,realtime,queue,%cpu,%mem,rss,vmem'
    }

    dag {
        enabled = true
        overwrite = true
        file = "${infodir}/${params.wf}-dag.svg"
    }
}

// Function to ensure that resource requirements don't go beyond a maximum limit
// Source: https://github.com/nf-core/rnaseq/blob/master/nextflow.config
def check_max(obj, max, type) {
    if (type == 'memory') {
        try {
            if (obj > max)
                return max
            else
                return obj
        } catch (all) {
            println "ERROR - Max memory '${params.max_memory} GB' is not valid! Using default value: $obj"
            return obj
        }
    } else if (type == 'time') {
        try {
            max_time = (params.max_time).m
            if (obj > max)
                return max
            else
            return obj
        } catch (all) {
            println "ERROR - Max time '${params.max_time} minutes' is not valid! Using default value: $obj"
            return obj
        }
    } else if (type == 'cpus') {
        try {
            if (obj == 'request') {
                return max
            } else {
                //return Math.min(obj, max) <- Error found
                return 2
            }
        } catch (all) {
            println "ERROR - Max cpus '${Math.min(obj, max)}' is not valid! Using default value: ${max}"
            return obj
        }
    }
}

def check_path(file_path) {
    // Try relative first
    launchDir = System.properties['user.dir']
    relative_path = "${launchDir}/${file_path}"
    File file_obj = new File(relative_path)
    if (file_obj.exists()) {
        return relative_path
    } else {
        // Try as absolute path
        file_obj = new File(file_path)
        if (file_obj.exists()) {
            return file_path
        } else {
            println "ERROR - Unable to locate '${params.nfconfig}' please check it exists"
        }
    }
}
