#!/usr/bin/env python

#import birchenv
import copy
import os
import os.path
import subprocess
import sys

# Wrapper for tbl2asn March 3, 2020
"""
We need to run tbl2asn through a wrapper because the NCBI tbl2asn
binary needs one or more libraries, including libidn.so.11.
The solution is to run tbl2asn from a script that puts the libraries
into LD_LIBRARY_PATH or DYLD_LIBRARY_PATH. 
Using a bash script,I have been unable to get tbl2asn from a  to run
using the -j option, escaping in all possible ways single and double quotes.
For some reason, running tbl2asn works from a Python script.  
"""

if 'BIRCH' in os.environ:
    BIRCH = os.environ.get('BIRCH')
    print('BIRCH=' + BIRCH)
else :
    print('tbl2asn.py: BIRCH environment variable not set')
    exit(1)

if 'BIRCH_PLATFORM' in os.environ:
    BIRCH_PLATFORM = os.environ.get('BIRCH_PLATFORM')
    print('BIRCH_PLATFORM=' + BIRCH_PLATFORM)

if 'LD_LIBRARY_PATH' in os.environ:
    LD_LIBRARY_PATH = os.environ.get('LD_LIBRARY_PATH')
else:
    LD_LIBRARY_PATH = ""
print('LD_LIBRARY_PATH=' + LD_LIBRARY_PATH)

if BIRCH_PLATFORM == 'osx-x86_64':
    subprocess.call(['open', os.path.join(BIRCH, 'lib-osx-x86_64', 'tbl2asn')])
else:

    BIRCHLIBS = ""
    if BIRCH_PLATFORM == "linux-intel":
        BIRCHLIBS = BIRCH + '/local/lib-linux-intel:' + BIRCH + '/lib-linux-intel'
    elif BIRCH_PLATFORM == "linux-x86_64":
        BIRCHLIBS = os.path.join(BIRCH, 'lib-', BIRCH_PLATFORM, 'tbl2asn')

    print('BIRCHLIBS=' + BIRCHLIBS)
    if BIRCHLIBS != "":
        if not LD_LIBRARY_PATH == "":
            LD_LIBRARY_PATH=BIRCHLIBS + os.pathsep + LD_LIBRARY_PATH
        else:
            LD_LIBRARY_PATH=BIRCHLIBS
    print('LD_LIBRARY_PATH=' + LD_LIBRARY_PATH)  
    os.environ["LD_LIBRARY_PATH"] = LD_LIBRARY_PATH
    
    cmd_run = copy.copy(sys.argv)
    cmd_run[0] = 'tbl2asn.bin'
    print(cmd_run)
    subprocess.call(cmd_run, env=os.environ)
