#!python
"""Start the real `viame`, with libpython findable.

Generated by cmake/wheel/build_wheel.py. See the note beside LAUNCHER there
for why this is not simply the binary.
"""
import os
import sys
import sysconfig


def main():
    real = os.path.join(sys.prefix, "libexec", "viame")

    if not os.path.exists(real):
        sys.exit("viame: {{}} is missing; the install is incomplete".format(real))

    # Applets invoke python and other tools by name. Keep them in the same
    # environment even when this launcher is called by its absolute path.
    os.environ["PATH"] = os.path.dirname(sys.executable) + os.pathsep + os.environ.get("PATH", "")

    # Pipeline templates can refer to $ENV{VIAME_INSTALL}. Resolve that
    # against this environment when no explicit installation was selected.
    os.environ.setdefault("VIAME_INSTALL", sys.prefix)

    # The tool embeds CPython, and an embedded interpreter builds sys.path
    # from the interpreter it links rather than from the environment the tool
    # was installed into, so `import viame` has to be pointed at it. Without
    # this the python-registered plugins are missing and nothing says so.
    site = sysconfig.get_path("purelib")
    existing = os.environ.get("PYTHONPATH", "")
    if site not in existing.split(os.pathsep):
        os.environ["PYTHONPATH"] = os.pathsep.join(
            [site] + ([existing] if existing else []))

    # Main uses dynamic plugins; lite registers its built-in plugins. Locate
    # any packaged plugin directories instead of relying on build-machine paths.
    plugin_dirs = []
    for family, categories in (("kwiver/plugins", ("algorithms", "modules", "processes", "applets")),
                               ("viame", ("modules", "processes", "applets"))):
        for category in categories:
            directory = os.path.join(sys.prefix, "lib", family, category)
            if os.path.isdir(directory):
                plugin_dirs.append(directory)
    if plugin_dirs:
        existing = os.environ.get("KWIVER_PLUGIN_PATH", "")
        os.environ["KWIVER_PLUGIN_PATH"] = os.pathsep.join(plugin_dirs + ([existing] if existing else []))
        os.environ.setdefault("KWIVER_PLUGIN_PATH_NO_DEFAULTS", "1")

    # A pipeline's `include` is resolved against the working directory, this
    # variable, and the standard locations under the executable's parent. The
    # tools live in `libexec`, not one level below the prefix, so the last of
    # those misses the configs shipped beside them and an absolute path to a
    # .pipe failed on its first include from anywhere but that directory.
    config_dirs = [os.path.join(sys.prefix, "configs", "pipelines"),
                   os.path.join(sys.prefix, "configs")]
    config_dirs = [d for d in config_dirs if os.path.isdir(d)]
    if config_dirs:
        existing = os.environ.get("KWIVER_CONFIG_PATH", "")
        os.environ["KWIVER_CONFIG_PATH"] = os.pathsep.join(
            config_dirs + ([existing] if existing else []))

    # Where this interpreter keeps libpython. A standalone build keeps it to
    # itself, and the loader will not find it without being told.
    paths = []
    for var in ("LIBDIR", "LIBPL"):
        value = sysconfig.get_config_var(var)
        if value and os.path.isdir(value):
            paths.append(value)

    if paths:
        existing = os.environ.get("LD_LIBRARY_PATH", "")
        merged = [p for p in paths if p not in existing.split(os.pathsep)]
        if merged:
            os.environ["LD_LIBRARY_PATH"] = os.pathsep.join(
                merged + ([existing] if existing else []))

    try:
        os.execv(real, [real] + sys.argv[1:])
    except OSError as e:
        sys.exit("viame: cannot run {{}}: {{}}".format(real, e))


if __name__ == "__main__":
    main()
