from distutils.core import setup, Extension
import os, sysconfig
import subprocess

gidpost_dir = "../source/"

# Common flags for both release and debug builds.
extra_compile_args = sysconfig.get_config_var('CFLAGS').split()

include_dirs = [
    os.getcwd(),  # '.',
    gidpost_dir,
]
    # os.environ[ 'HOME' ] + 'include',
    # os.path.join(os.getcwd(), 'include'),

# hdf5_include = subprocess.check_output( [ "pkg-config", "hdf5", "--cflags"]).decode().split()
# if hdf5_include != "":
#     extra_compile_args += [ "-DENABLE_HDF5" ]
#     extra_compile_args += hdf5_include
hdf5_flag_list = subprocess.check_output( [ "h5cc", "-show", "-shlib"]).decode().split()
if hdf5_flag_list != "":
    extra_compile_args += [ "-DENABLE_HDF5" ]
    # extra_compile_args += hdf5_include
    for h5_opt in hdf5_flag_list:
        if ( h5_opt.startswith( '-I')):
            extra_compile_args += [ h5_opt ]
zlib_include = subprocess.check_output( [ "pkg-config", "zlib", "--cflags"]).decode().split()
if zlib_include != "":
    extra_compile_args += zlib_include

library_dirs = [  # path to .a or .so file(s)
    os.getcwd(),
 ]
# os.environ[ 'HOME' ] + 'lib',

extra_link_args = sysconfig.get_config_var( 'LDFLAGS' ).split()

# hdf5_libs = subprocess.check_output( [ "pkg-config", "hdf5", "--libs"]).decode().split()
# if hdf5_libs != "":
#     extra_link_args += hdf5_libs
#     extra_link_args += [ "-lhdf5_hl"]
if hdf5_flag_list != "":
    for h5_opt in hdf5_flag_list:
        if ( h5_opt.startswith( '-L') or h5_opt.startswith( '-lhdf5')):   # only want -lhdf5 and -lhdf5_hl, an not -lsz, ...
            extra_link_args += [ h5_opt]
zlib_libs = subprocess.check_output( [ "pkg-config", "zlib", "--libs"]).decode().split()
if zlib_libs != "":
    extra_link_args += zlib_libs

extra_link_args += [ "-lm" ]

gidpost_module = Extension(
    "_gidpost",
    sources = [
        # "gidpostmodule.c",
        "gidpost_module_wrap.c",
        gidpost_dir + "gidpost.c",
        gidpost_dir + "gidpostFILES.c",
        gidpost_dir + "gidpostInt.c",
        gidpost_dir + "gidpostHash.c",
        gidpost_dir + "hashtab.c",
        gidpost_dir + "recycle.c",
        gidpost_dir + "lookupa.c",
        gidpost_dir + "hdf5c.c",
        gidpost_dir + "gidpostHDF5.c",
    ],
    include_dirs = include_dirs,
    library_dirs = library_dirs,
    extra_compile_args = extra_compile_args,
    extra_link_args = extra_link_args
)

setup(
    name = "gidpost",
    version = "1.0",
    description = "GiDpost writer module.",
    ext_modules = [ gidpost_module ],
)
