#!/usr/bin/env python3
# -*- python -*-
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis <michael.aivazis@para-sim.com>
# (c) 1998-2024 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.12.4"
    # 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
    _mm_prefix = pyre.primitives.path(__file__).resolve().parent
    # check whether i'm running from my source directory
    _mm_insitu = (_mm_prefix / "make").exists()

    # if i'm running in-place
    if _mm_insitu:
        # this is the layout i expect to see:
        # the {portinfo} headers
        _mm_incdir = _mm_prefix / "include" / "mm"
        # the share area
        _mm_shrdir = _mm_prefix
        # my makefiles
        _mm_mkdir = _mm_shrdir / "make"
    # otherwise
    else:
        # assume i am installed in a u*ixy environment:
        # the {portinfo} headers
        _mm_incdir = (_mm_prefix / ".." / "include" / "mm").resolve()
        # my share area
        _mm_shrdir = (_mm_prefix / ".." / "share" / "mm").resolve()
        # my makefiles
        _mm_mkdir = (_mm_shrdir / "make").resolve()

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


# end of file
