#!python3

import os
import shutil
import subprocess
import sys

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.abspath(os.path.dirname(SCRIPT_DIR))
sys.path.insert(0, ROOT_DIR)

import fix_rpath

LIB_DIR = os.path.join(SCRIPT_DIR, "lib")
if not os.path.exists(LIB_DIR):
    os.makedirs(LIB_DIR)

os.environ["MACOSX_DEPLOYMENT_TARGET"]="10.10"

METIS_INST = os.path.abspath(os.path.join(
    ROOT_DIR, "metis-5.1.0", "INSTALL_shared_Release"))
os.environ["LMETISDIR"] = os.path.join(METIS_INST, "lib")
os.environ["IMETIS"] = os.path.join(METIS_INST, "include")

print(os.environ["LMETISDIR"])

print(os.environ["IMETIS"])

subprocess.call(["make"])

if sys.platform == "darwin":
    COPY_DYLIBS = ["/usr/local/gcc-7.1/lib/libgfortran.4.dylib",
                   "/usr/local/gcc-7.1/lib/libgcc_s.1.dylib",
                   "/usr/local/gcc-7.1/lib/libquadmath.0.dylib"]
    for lib in COPY_DYLIBS:
        shutil.copy(lib, LIB_DIR)

    for subdir, dirs, files in os.walk(LIB_DIR):
        for afile in files:
            if afile.endswith("dylib"):
                for lib in COPY_DYLIBS:
                    pos = lib.rfind('/')
                    if lib[pos+1:] != afile:
                        rpath_name = '@rpath' + lib[pos:]
                        print("install_name_tool -change " +  lib + " " + rpath_name + " " + LIB_DIR + afile)
                        os.system("install_name_tool -change " +  lib + " " + rpath_name + " " + LIB_DIR + "/" + afile)

fix_rpath.fix_rpath_libraries(LIB_DIR)
