#!/usr/bin/env python
"""
Wrapper script that uses statically compiled coreir binary distribution only if
coreir is not already present in the path
"""

import platform
import sys
import os
import coreir
import subprocess
import shutil


# If coreir is not present in the path, try using the static binary
# distribution, this gives priority to the system installed version as we
# assume that is what the user wants (e.g. buildling a custom version)
if shutil.which("coreir") != __file__:
    _system = platform.system()
    if _system == "Linux":
        LIBRARY_PATH_VAR = "LD_LIBRARY_PATH"
    elif _system == "Darwin":
        LIBRARY_PATH_VAR = "DYLD_LIBRARY_PATH"
    else:
        raise NotImplementedError(_system)

    path = os.path.abspath(os.path.dirname(coreir.__file__))
    coreir_binary = os.path.join(path, "coreir")
    env = dict(os.environ)
    env[LIBRARY_PATH_VAR] = path
    subprocess.call([coreir_binary] + sys.argv[1:], env=env)
else:
    subprocess.call(["coreir"] + sys.argv[1:])
