#!/usr/bin/python3
"""lamboot-inspect — LamBoot diagnostic tool.

Thin entry-point shim. All logic lives in the lamboot_inspect package.
"""
import os
import sys


def _bootstrap() -> None:
    """Make the sibling ``lamboot_inspect`` package importable.

    This script may be invoked:
      * From a source checkout (e.g. ``tools/lamboot-inspect``)
      * From ``dist/`` after package-release.sh stages it
      * Symlinked onto ``PATH`` (``/usr/local/bin/lamboot-inspect``)

    Resolve the real script path (following any symlinks) and add the
    containing directory to ``sys.path`` so ``import lamboot_inspect``
    succeeds in every layout.
    """
    here = os.path.dirname(os.path.realpath(__file__))
    if here not in sys.path:
        sys.path.insert(0, here)


# Where an installed copy of this tool lives: LamBoot's own packages, the
# lamboot-tools packages, and a `make install` of either under /usr/local.
_INSTALL_DIRS = (
    "/usr/share/lamboot",
    "/usr/lib/lamboot-tools",
    "/usr/local/share/lamboot",
    "/usr/local/lib/lamboot-tools",
)


def _copy_version(directory: str, trusted_only: bool = True):
    """The version of the copy installed in `directory`, as a tuple, or None.

    With `trusted_only`, a directory that root doesn't own, or that others
    can write, has no version: a copy someone else could have written is
    never run in place of this one. The running copy's own version is read
    without that test. It is already running, and treating it as version
    zero made it hand over to any older copy root did own (a test VM whose
    /usr/share/lamboot directory was left owned by a user ran a 0.9.0 copy
    from /usr/local instead of the packaged 0.17.0).
    """
    import re

    try:
        st = os.stat(directory)
        if trusted_only and (st.st_uid != 0 or st.st_mode & 0o022):
            return None
        if not os.path.isfile(os.path.join(directory, "lamboot-inspect")):
            return None
        with open(os.path.join(directory, "lamboot_inspect", "__init__.py")) as f:
            m = re.search(r'^\s*__version__ = "(\d+)\.(\d+)\.(\d+)"', f.read(), re.M)
    except OSError:
        return None
    return tuple(int(x) for x in m.groups()) if m else None


def _newer_installed_copy(here: str, dirs=_INSTALL_DIRS):
    """Another installed copy newer than this one, or None.

    LamBoot's package and lamboot-tools both ship lamboot-inspect, and PATH
    decides which one a shell finds. Whichever starts hands over to the
    newest, so an older copy earlier on PATH doesn't hide a newer one. Only
    an installed copy does this: one run from a source tree or an unpacked
    tarball was asked for by path and runs as it is.
    """
    real = [os.path.realpath(d) for d in dirs]
    if here not in real:
        return None
    own_version = _copy_version(here, trusted_only=False)
    if own_version is None:
        return None
    best, best_version = None, own_version
    for d in real:
        if d == here:
            continue
        v = _copy_version(d)
        if v is not None and v > best_version:
            best, best_version = d, v
    return best


def _hand_over_to_newer_copy() -> None:
    if os.environ.get("LAMBOOT_INSPECT_NO_HANDOVER"):
        return
    here = os.path.dirname(os.path.realpath(__file__))
    newer = _newer_installed_copy(here)
    if newer is None:
        return
    os.environ["LAMBOOT_INSPECT_NO_HANDOVER"] = "1"
    script = os.path.join(newer, "lamboot-inspect")
    try:
        os.execv(sys.executable, [sys.executable, script] + sys.argv[1:])
    except OSError:
        return


def _require_python(major: int, minor: int) -> None:
    if sys.version_info < (major, minor):
        sys.stderr.write(
            f"lamboot-inspect requires Python {major}.{minor} or newer "
            f"(you have {sys.version.split()[0]})\n"
        )
        sys.exit(1)


if __name__ == "__main__":
    _require_python(3, 9)
    _hand_over_to_newer_copy()
    _bootstrap()
    try:
        from lamboot_inspect.cli import main
    except ImportError as e:
        sys.stderr.write(
            f"lamboot-inspect: could not load lamboot_inspect package: {e}\n"
            "Is the tools/lamboot_inspect/ directory adjacent to this script?\n"
        )
        sys.exit(1)
    sys.exit(main(sys.argv[1:]))
