

rule busco:
    """Busco wrapper

    Required input:
        - __busco__input: the output of an assembly analysis (e.g. from canu)

    Required output:
        - __busco__output: lots of output generated. We look for the 
          full_table_{sample}.tsv file

    Required parameters:
        - __busco__workdir: where to save the results of the analysis

    Required log:
        - __busco__log: where to save the stderr

    Required configuration:
        .. code-block:: yaml

            # 
            busco:
                mode_choice: genome, transcriptomics, proteins
                species: name of a BUSCO dataset. (use Sequanix to get the list)
                options: any options understood by busco

    Internally, we set the environmental variable, create a 
    config.ini file populated with conda environmental variable.

    Temporary directory created by busco is deleted manually.

    """
    input: __busco__input
    output: __busco__output
    params:
        mode    = config['busco']['mode_choice'],
        options = config['busco']['options'],
        wkdir   =  __busco__workdir,
        species = config['busco']['species_choice'],
    log: __busco__log
    threads: config['busco']["threads"]
    run:
        import os
        from sequana import busco

        sample_name = params.wkdir.split(os.sep)[0]

        try:
            conda_bin_path = os.environ['CONDA_PREFIX'] + os.sep +"bin"
            augustus_config_path = os.environ['CONDA_PREFIX'] + os.sep +"config"
        except KeyError:
            conda_bin_path = os.environ['CONDA_ENV_PATH'] + os.sep +"bin"
            augustus_config_path = os.environ['CONDA_ENV_PATH'] + os.sep +"config"

        config = busco.BuscoConfig(
            params.species,
            sample_name=sample_name,
            outpath=params.wkdir,
            conda_bin_path=conda_bin_path,
            Rscript_bin_path="", # not required by our analysis
            tmp_path="./tmp_{}".format(sample_name)
        )
        config_filename = params.wkdir + "/config.ini"
        config.save_config_file(config_filename)

        cmd = "export BUSCO_CONFIG_FILE={};".format(config_filename)
        cmd += "export AUGUSTUS_CONFIG_PATH={} ;".format(augustus_config_path)
        cmd += "run_busco -i {input[0]} -m {params.mode} -c {threads} -f 2>>{log};"

        # -f to force overwritten existing files
        shell(cmd)
        shell("rm -rf ./tmp_{}".format(sample_name))











