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

process GET_GENOME_LENGHT {

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

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

    input:
    path reference_genome

    output:
    path "${ref_dir}_circos.genome", emit: circos_genome_len_ch
    path "${ref_dir}.genome", emit: genome_len_ch

    script:
    """
    if [ ! -f ${reference_genome}.fai ]; then
    echo "Samtools index file not found!"
    samtools faidx ${reference_genome}
    fi
    awk -v OFS='\t' {'print \$1,"0",\$2,\$1,\$1'} ${reference_genome}.fai > ${ref_dir}_circos.genome

    cat ${reference_genome} | awk '\$0 ~ \">\" {if (NR > 1) {print c;} c=0;printf substr(\$0,2,100) \"\\t\"; } \$0 !~ \">\" {c+=length(\$0);} END { print c; }' > ${ref_dir}.genome
    """
}
