#!/usr/bin/env python3
# -*- python -*-
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis <michael.aivazis@para-sim.com>
# (c) 1998-2026 all rights reserved

# externals
import os
import re
import subprocess
import sys
import tempfile
import typing
import urllib.request

# attempt to
try:
    # access the framework
    import pyre
# if it's not accessible
except ImportError:
    # for the pyre repo
    _pyre_repo = "https://github.com/pyre/pyre/releases/download"
    # we will download the canonical version
    _pyre_release = "v1.13.0"
    # of the bootstrapping archive
    _pyre_boot = "pyre-boot.zip"
    # and deposit it in a temporary directory
    _mm_pyre = os.path.join(tempfile.mkdtemp(), _pyre_boot)
    # if the file is not already there
    if not os.path.exists(_mm_pyre):
        # form the source url
        _pyre_url = f"{_pyre_repo}/{_pyre_release}/{_pyre_boot}"
        # show me
        print(f"downloading '{_pyre_url}")
        # and grab the archive from the wed
        with urllib.request.urlopen(url=_pyre_url) as istream:
            # open the local file
            with open(_mm_pyre, "wb") as ostream:
                # pull data and write it out
                ostream.write(istream.read())
    # add the pyre archive to the path, right after the cwd
    sys.path.insert(1, _mm_pyre)
    # and try importing the framework once more
    import pyre
# if nothing went wrong
else:
    # leave a marker, just in case someone cares
    _mm_pyre = None

# get the package
import merlin

# bootstrap
if __name__ == "__main__":
    # find out where i live; the driver sits in {bin}, so my home is one level up
    _mm_home = pyre.primitives.path(__file__).resolve().parent.parent
    # check whether i'm running from my source directory; only the source tree keeps the
    # {portinfo} headers under {lib/mm} -- the install stages them into {include/mm}, so
    # their location is what tells the two layouts apart
    _mm_insitu = (_mm_home / "lib" / "mm" / "portinfo.h").exists()

    # if i'm running in place, the headers are where the sources left them
    if _mm_insitu:
        # so mark against the source directory
        _mm_incdir = _mm_home / "lib" / "mm"
    # otherwise
    else:
        # they were staged into the include area of the install prefix
        _mm_incdir = _mm_home / "include" / "mm"

    # either way, the make engine sits in the share area
    _mm_mkdir = _mm_home / "share" / "mm" / "make"

    # instantiate the app
    app = merlin.shells.mm(name="mm", engine=_mm_mkdir, portinfo=_mm_incdir)
    # invoke
    status = app.run()
    # and share the status with the shell
    raise SystemExit(status)


# end of file
