#!/usr/bin/env python

import Cython.Build
import setuptools
import sysconfig
import subprocess

libname = "cnorxz"
author = "Christian Zimmermann"
author_email = "chizeta@f3l.de"
expected_cnorxz_version = "1.0.0" # dummy for now; in the future this is supposed to be the c++ version which is guaranteed to be compatible with py cnorxz

git_hash = subprocess.run(['git','rev-parse','HEAD'],stdout=subprocess.PIPE).stdout.decode('ascii')[:-1]
git_tags = subprocess.run(['git', 'tag', '-l', '--sort=refname', 'v*'],stdout=subprocess.PIPE).stdout.decode('ascii').split()

version = git_hash[:7]
if len(git_tags) != 0:
    git_tag = git_tags[-1]
    git_hash_tag = subprocess.run(['git','rev-parse',git_tag],stdout=subprocess.PIPE).stdout.decode('ascii')[:-1]
    if git_hash_tag == git_hash:
        version = git_tag[1:]
    else:
        version += git_tag[1:] 

# if expected_cnorxz_version != cnorxz_version
#    version += '-cxz' + cnorxz_version
        
path_to_cnorxz = "/home/chizeta/repos/cnorxz/install"

inc_dirs = list()
if path_to_cnorxz != "":
    inc_dirs.append( path_to_cnorxz + "/include/cnorxz" )

lib_dirs = list()
lib_dirs.append( "/usr/lib" )
lib_dirs.append( "/usr/local/lib" )
if path_to_cnorxz != "":
    inc_dirs.append( path_to_cnorxz + "/lib" )
lib_dirs.append( "/home/chizeta/repos/cnorxz/install/lib" )

extra_compile_args = sysconfig.get_config_var('CFLAGS').split()
extra_compile_args += ["-std=c++17", "-Wall", "-Wextra", "-Wpedantic"] # get this automatically from cnorxz itself??

default_extension_args = dict(
    language = "c++",
    include_dirs = inc_dirs,
    libraries = [libname],
    library_dirs = lib_dirs,
    extra_compile_args = extra_compile_args,
)

if __name__ == "__main__":
    print("Include directories:")
    for d in inc_dirs:
        print("\t",d)
    print("Library directories:")
    for d in lib_dirs:
        print("\t",d)

    extensions = list()
    extensions.append(
        setuptools.Extension(
            name = libname + ".base",
            sources = [
                "cnorxz/base/ranges.pyx",
                #"cnorxz/base/array.pyx",
            ],
            **default_extension_args
        )
    )
    # append further extensions (cereal, hdf5, mpi ...) here
    
    setuptools.setup(
        name = libname,
        packages = setuptools.find_packages(),
        version = version,
        include_dirs = inc_dirs,
        ext_modules = Cython.Build.cythonize(extensions),
        author = author,
        author_email = author_email,
    )