#! /usr/bin/env python

from __future__ import print_function
import platform, sysconfig, os, sys
from glob import glob


## Build dirs
srcdir = os.path.abspath("@abs_top_srcdir@/src")
libdir = os.path.abspath("@abs_top_builddir@/src/.libs")
incdirs = [os.path.abspath("@abs_top_srcdir@/include"),
           os.path.abspath("@abs_top_builddir@/include"),
           os.path.abspath("@abs_srcdir@/rivet"),
           os.path.abspath("@abs_builddir@/rivet")]

## Library-search dirs
@ENABLE_HEPMC_3_TRUE@lookupdirs = ["@HEPMC3LIBPATH@"]
@ENABLE_HEPMC_3_FALSE@lookupdirs = ["@HEPMCLIBPATH@"]
lookupdirs += ["@FASTJETLIBPATH@", "@YODALIBPATH@"]


## The extension source file (built by separate Cython call)
# TODO: Move the Cython call in here, via Cython API?
srcpath = '@abs_builddir@/rivet/core.cpp'
if not os.path.isfile(srcpath): # distcheck has it in srcdir
    srcpath = os.path.relpath("@abs_srcdir@/rivet/core.cpp")

## Include args
incargs = " ".join("-I{}".format(d) for d in incdirs)
incargs += " -I@prefix@/include"
incargs += " @HEPMCCPPFLAGS@ @HEPMC3CPPFLAGS@ @FASTJETCPPFLAGS@ @YODACPPFLAGS@"
incargs += " @CPPFLAGS@"
incargs += " -I" + sysconfig.get_config_var("INCLUDEPY")

## Compile args
cmpargs = "@PYEXT_CXXFLAGS@"
cmpargs += " @CXXFLAGS@"

## Link args -- base on install-prefix, or on local lib dirs for pre-install build
linkargs = " ".join("-L{}".format(d) for d in lookupdirs)
linkargs += " -L@abs_top_builddir@/src/.libs" if "RIVET_LOCAL" in os.environ else "-L@prefix@/lib"
## This needs to be passed separately on Mac, otherwise HepMC3 library won't be found
@ENABLE_HEPMC_3_TRUE@if platform.system() == "Darwin": linkargs += " -Wl,-rpath,@HEPMC3LIBPATH@"
linkargs += " @LDFLAGS@"

## Library args
@ENABLE_HEPMC_3_TRUE@libraries = ["HepMC3"]
@ENABLE_HEPMC_3_FALSE@libraries = ["HepMC"]
libraries += ["fastjet", "YODA", "Rivet"]
libargs = " ".join("-l{}".format(l) for l in libraries)

# print("\n")
# print("CONFIG VARS")
# for k, v in sysconfig.get_config_vars().items():
#     print("  ", k, ": ", v)
# print("\n")
# for k in ["INCLUDEPY", "LIBPL", "LDLIBRARY", "LIBS", "LIBM", "LINKFORSHARED", "SO"]:
#     print(k, "::", sysconfig.get_config_var(k))
# print("\n")
# print(glob(os.path.join(sysconfig.get_config_var("LIBPL"), "*")))
# print(glob(os.path.join(sysconfig.get_config_var("LIBPL"), "libpython*.*")))
# print(glob(os.path.join(sysconfig.get_config_var("LIBPL"), "libpython*"+sysconfig.get_config_var("SO")+"*")))
# print("\n")

## Python compile/link args
pyargs = "-I" + sysconfig.get_config_var("INCLUDEPY")
libpys = [os.path.join(sysconfig.get_config_var(ld), sysconfig.get_config_var("LDLIBRARY")) for ld in ["LIBPL", "LIBDIR"]]
libpys.extend( glob(os.path.join(sysconfig.get_config_var("LIBPL"), "libpython*.*")) )
libpys.extend( glob(os.path.join(sysconfig.get_config_var("LIBDIR"), "libpython*.*")) )
libpy = None
for lp in libpys:
    if os.path.exists(lp):
        libpy = lp
        break
if libpy is None:
    print("No libpython found in expected location exiting")
    print("Considered locations were:", libpys)
    sys.exit(1)
pyargs += " " + libpy
pyargs += " " + sysconfig.get_config_var("LIBS")
pyargs += " " + sysconfig.get_config_var("LIBM")
#pyargs += " " + sysconfig.get_config_var("LINKFORSHARED")


## Assemble the compile & link command
compile_cmd = "  ".join([os.environ.get("CXX", "g++"), "-shared -fPIC", "-o core.so",
                         srcpath, incargs, cmpargs, linkargs, libargs, pyargs])
print("Build command =", compile_cmd)


## (Re)make the build/rivet dir and copy in Python sources
import shutil
try:
    shutil.rmtree("build/rivet")
except:
    pass
try:
    os.makedirs("build/rivet")
except FileExistsError:
    pass
for pyfile in glob("@srcdir@/rivet/*.py"):
    shutil.copy(pyfile, "build/rivet/")
shutil.copytree("@srcdir@/rivet/hepdatapatches", "build/rivet/hepdatapatches")
shutil.copytree("@srcdir@/rivet/plotting", "build/rivet/plotting")

## Run the extension compilation in the build/rivet dir
import subprocess
sys.exit(subprocess.call(compile_cmd.split(), cwd="@abs_builddir@/build/rivet"))
