#!/usr/bin/env bash
VERSION=3.0.0
CONDA_ENV=$(which bactopia | sed 's=bin/bactopia==')
BACTOPIA_NF="${CONDA_ENV}/share/bactopia-${VERSION}" 

# If no user input, print usage
if [[ $# == 0 ]]; then
    echo "bactopia - v${VERSION}"
    echo ""
    echo "Available Commands"
    echo "bactopia - Execute the Bactopia Nextflow pipeline"
    echo ""
    echo "bactopia citations - Print citation for datasets, tools and Bactopia"
    echo ""
    echo "bactopia datasets - Download optional datasets to supplement your analyses with Bactopia"
    echo ""
    echo "bactopia download - Build Bactopia Conda, Docker,and or Singularity environments "
    echo ""
    echo "bactopia prepare - Create a 'file of filenames' for input FASTQ files"
    echo ""
    echo "bactopia search - Query Taxon ID or Study Accession against ENA for input accessions"
    echo ""
    echo "bactopia summary - Generate a summary table from the Bactopia results"
    echo ""
    echo "bactopia --citation - Print the Bactopia citation"
    echo "bactopia --version - Print the Bactopia version"
    echo ""
    echo "Print Usages:"
    echo "bactopia --help"
    echo "bactopia citations --help"
    echo "bactopia download --help"
    echo "bactopia prepare --help"
    echo "bactopia search --help"
    echo "bactopia summary --help"
    echo ""
    echo "Example Commands"
    echo "bactopia --R1 SAMPLE_R1.fastq.gz --R2 SAMPLE_R2.fastq.gz --sample SAMPLE"
    echo "bactopia --wf pangenome --bactopia /path/to/bactopia/results"
    echo ""
    echo "bactopia download --use_defaults"
    echo ""
    echo "bactopia prepare --path my-fastq-dir > my-fastqs.txt"
    echo "bactopia --fastqs my-fastqs.txt"
    echo ""
    echo "bactopia search --query PRJNA480016 --limit 20"
    echo "bactopia --accessions ena-accessions.txt"
    echo ""
    echo "bactopia summary --bactopia /path/to/bactopia/results"
    echo ""
    exit
fi

if [[ "$1" == "prepare" ]]; then
    bactopia-prepare "${@:2}"
elif [[ "$1" == "search" ]]; then
    bactopia-search "${@:2}"
elif [[ "$1" == "datasets" ]]; then
    bactopia-datasets --bactopia-path "${BACTOPIA_NF}" "${@:2}"
elif [[ "$1" == "download" ]]; then
    bactopia-download --bactopia-path "${BACTOPIA_NF}" "${@:2}"
elif [[ "$1" == "citation" ]] || [[ "$1" == "--citation" ]]; then
    echo "Petit III RA, Read TD, Bactopia: a flexible pipeline for complete analysis of bacterial "
    echo "genomes. mSystems. 5 (2020), https://doi.org/10.1128/mSystems.00190-20"
elif [[ "$1" == "citations" ]]; then
    bactopia-citations --bactopia-path "${BACTOPIA_NF}" "${@:2}"
elif [[ "$1" == "summary" ]]; then
    bactopia-summary "${@:2}"
elif [[ "$1" == "version" ]] || [[ "$1" == "--version" ]]; then
    echo "bactopia ${VERSION}"
else
    # Check if Conda environments need to be built
    PREBUILD=1
    BUILD_TYPE="conda"
    if [[ "$*" == *"singularity"* ]] || [[ "$*" == *"slurm"* ]] || [[ "$*" == *"sge"* ]] || [[ "$*" == *"arcc"* ]]; then
        BUILD_TYPE="singularity"
    elif  [[ "$*" == *"docker"* ]] || [[ "$*" == *"arm"* ]]; then
        BUILD_TYPE="docker"
    fi

    # If these are used, skip prebuild
    CHECKS=("help" "help_all" "nfconfig" "list_wfs") 
    for check in "${CHECKS[@]}"; do
        if [[ "$*" == *"${check}"* ]]; then
            PREBUILD=0
        fi
    done

    if [[ "${PREBUILD}" -eq 1 ]]; then
        BUILD_OPTS=""
        if [[ "$*" == *"arcc"* ]]; then
            # Get singularity cache from config
            BUILD_OPTS=$(grep "singularity_cache =" ${BACTOPIA_NF}/conf/profiles/arcc.config | sed "s/^.* = //;s/'//g;s/^/--singularity_cache /")
        fi

        # Build conda/docker/singularity envs, rebuild out of sync envs, skip existing
        bactopia-download --bactopia-path "${BACTOPIA_NF}" --envtype "${BUILD_TYPE}" ${BUILD_OPTS} "${@:1}"
    fi

    # Create custom work dir
    WORK_DIR=""
    WORK_ARG=""
    CAN_CLEAN_UP=1
    if echo "$*" | sed -r 's/ ([-]+)/\n\1/g' | grep "^-w \|-work-dir" > /dev/null; then
        # User specified a work directory
        CAN_CLEAN_UP=0
    else
        # User did not specify a work directory, we'll use custom one based on workflow name
        WORK_DIR="$(pwd)/work/${WF}"
        WORK_ARG="-w ${WORK_DIR}"
    fi

    # Execute Bactopia Nextflow pipeline
    OPTS="${WORK_ARG}"
    if nextflow run "${BACTOPIA_NF}/main.nf" ${OPTS} "${@:1}"; then
        # bactopia finished successfully
        if [[ "$*" == *"--cleanup_workdir"* ]] && [[ "${CAN_CLEAN_UP}" -eq 1 ]]; then
            # user asked for work dir to be cleaned up
            echo "Bactopia finished successfully! Found '--cleanup_workdir' removing '${WORK_DIR}'"
            rm -rf "${WORK_DIR}"
        fi
    else
        exit $?
    fi
fi
