#!python
from __future__ import print_function
import os
import subprocess
import sys
import shutil

GCC_VERSION = "11.3.0"


def find_glibc_location():
    # only valid for linux
    ls_path = shutil.which("ls")
    raw_output = subprocess.check_output(["ldd", ls_path]).decode("ascii")
    lines = raw_output.split("\n")
    for line in lines:
        line = line.strip()
        tokens = line.split(" ")
        if tokens[1] != "=>":
            continue
        if "libc.so" in tokens[0]:
            p = tokens[2]
            return os.path.dirname(p)
    return None


def find_glibc_header():
    # hardcode path for now
    return "/usr/include/:/usr/include/x86_64-linux-gnu"


root_dir = None
for dirname in sys.path:
    path = os.path.join(dirname, "fsim")
    if os.path.exists(os.path.join(path, "bin", "fsim")):
        root_dir = path
        break
if root_dir is None:
    print("unable to find fsim", file=sys.stderr)
    exit(1)

bin_dir = os.path.join(root_dir, "bin")
fsim_bin = os.path.join(bin_dir, "fsim")
cxx_bin = os.path.join(bin_dir, "g++-" + GCC_VERSION)

if os.path.exists(cxx_bin):
    # also need to find out the library path for crt1.o etc
    glibc_path = find_glibc_location()
    if glibc_path is None:
        print("unable to find glibc", file=sys.stderr)
        exit(1)
    # find glibc headers
    cpath = find_glibc_header()
    env = {"FSIM_CXX": cxx_bin, "LIBRARY_PATH": glibc_path + ":/usr/lib:/usr/lib64:/usr/lib/x86_64-linux-gnu/",
           "CPATH": cpath}
else:
    # use system default one
    env = {}
env.update(os.environ)
exit(subprocess.call([fsim_bin] + sys.argv[1:], env=env))
