#!/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

perl_script_path = "${workflow.projectDir}/bin/perl"
r_script_path = "${workflow.projectDir}/bin/R"
shell_script_path = "${workflow.projectDir}/bin/shell"

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

    container "tegreedy/nested:2.0.0"

    input:
    path reference

    output:
    path "nester_out/"

    script:
    """
    mkdir nester_out
    nested-nester -d nester_out -n 3 ${reference}
    """
}

process ANNOTATE_FRAGMENTS {
    //Find all repeat_fragments in TE-greedy-nester output and annotate them
    publishDir "${params.data_dir}/annotations", mode: 'copy', enabled: save_enabled

    input:
    path gff_dir

    output:
    path "${ref_dir}_fragments_annotated.gff", emit: annot_ch

    script:
    """
    find ${gff_dir}/ -name "*${params.gff_suffix}.gff" -exec cat {} \\; | grep \"fragment\\|polypeptide\" > ${ref_dir}_fragments.gff
    cat ${ref_dir}_fragments.gff | perl "${perl_script_path}/annotate_repeat_fragments.pl" > ${ref_dir}_fragments_annotated.gff
    """
}

process SHUFFLE_FRAGMENTS {
    //Generate a shuffled version of the annotation GFF file before bed intersect

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

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

    input:
    path frag_annot
    path genome_lenght

    output:
    path "${ref_dir}_fragments_annotated_shuffled.gff", emit: annot_shuff_ch

    script:
    """
    bedtools shuffle -i ${frag_annot} -g ${genome_lenght} > ${ref_dir}_fragments_annotated_shuffled.gff
    """
}
