#!/usr/bin/env python3

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

# Wrapper for Sequin May 20, 2023

if 'BIRCH' in os.environ:
    BIRCH = os.environ.get('BIRCH')
    print('BIRCH=' + BIRCH)
else :
    print('sequin.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', 'Sequin', 'Sequin.app')])
elif BIRCH_PLATFORM == 'macos-arm64':
    subprocess.call(['open', os.path.join(BIRCH, 'lib-macos-arm64', 'Sequin', 'Sequin.app')])
else:

    # Sequin for linux-intel needs to find libXm.so.2 and libXp.so.6, which are not included
    # in many linux distributions. BIRCHLIBS is put first in the search path because
    # systems with older versions of libXm.so.2 will cause "Segmentation fault"
    # errors at many places in Sequin. This way, local copies of libXm.so.2 can be
    # overridden.

    BIRCHLIBS = ""
    if BIRCH_PLATFORM == "linux-intel":
        BIRCHLIBS = BIRCH + '/local/lib-linux-intel:' + BIRCH + '/lib-linux-intel'
    elif BIRCH_PLATFORM == "linux-x86_64":
        BIRCHLIBS = BIRCH + '/local/lib-linux-x86_64:' + BIRCH + '/lib-linux-x86_64'
    #if BIRCH_PLATFORM == "solaris-sparc":
        #BIRCHLIBS = "$BIRCH/local/lib-solaris-sparc:$BIRCH/lib-solaris-sparc"
    #elif BIRCH_PLATFORM == "solaris-amd64")
        #BIRCHLIBS = "$BIRCH/local/lib-solaris-amd64:$BIRCH/lib-solaris-amd64"


    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] = 'sequin.bin'
    print(cmd_run)
    subprocess.call(cmd_run, env=os.environ)
