# Smakemake file for running BUSCO3.
# Run command '$ snakemake -s busco run_4' to run analysis on example data 4.fa
# Change to transcriptome by adding --config mode=transcriptome
# Parameters can be changed by changing config.json

# make sure augustus config is in path by:
# export AUGUSTUS_CONFIG_PATH=/path/to/augustus/config
# e.g. export AUGUSTUS_CONFIG_PATH=~/miniconda3/pkgs/augustus-3.2.3-boost1.60_0/config
import re, os
from os import environ
import shutil

configfile: "config.json"
folder = "intermediate_data/"
name=config["name"]
mode = config["mode"]
lineage = config["lineage"]
ref_name=config["reference_name"]

def get_reference(wildcards):
    if config["reference_path"]:
        return config["reference_path"]
    else:
        return rules.trinity.output

rule busco_ann:
    input:
        get_reference
    output:
        directory(folder+"run_"+ref_name)
    log:
        "logs/BUSCO_annotation_run_"+name+".log"
    threads:
        config["threads"]
    run:
        #Find the good way to call busco
        busco_script = shutil.which("run_busco") or shutil.which("run_BUSCO.py")

        #check presence of AUGUSTUS_CONFIG_PATH (singularity problem)        
        if environ.get('AUGUSTUS_CONFIG_PATH'):
            print ('AUGUSTUS_CONFIG_PATH set:'+environ.get('AUGUSTUS_CONFIG_PATH'))
        else:
           print ('AUGUSTUS_CONFIG_PATH absent')
           augustus_path = shutil.which("augustus")
           print ("augustus_path:"+augustus_path)
           augustus_config_path = augustus_path[:-12]
           augustus_config_path = augustus_config_path+"config"
           os.environ["AUGUSTUS_CONFIG_PATH"] = augustus_config_path
           print ("AUGUSTUS_CONFIG_PATH set to "+augustus_config_path)

        # Do analysis
        shell("""
        {busco_script} -c {threads} -i {input} -l {lineage} -o {ref_name} --tmp {folder}tmp -m {mode} -f | tee {log}
        mv run_{ref_name} {output}
        """)

# Have to move since since otherwise the busco config.ini file has to be changed for other output dir
