# Copyright 2012-2017 CNRS-UM LIRMM, CNRS-AIST JRL
#
# This file is part of eigen-qld.
#
# eigen-qld is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# eigen-qld is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with eigen-qld.  If not, see <http://www.gnu.org/licenses/>.

from __future__ import print_function
try:
  from setuptools import setup
  from setuptools import Extension
except ImportError:
  from distutils.core import setup
  from distutils.extension import Extension

from Cython.Build import cythonize

import hashlib
import os
import subprocess

from numpy import get_include as numpy_get_include

win32_build = os.name == 'nt'

this_path  = os.path.dirname(os.path.realpath(__file__))
with open(this_path + '/eigen_qld/__init__.py', 'w') as fd:
    fd.write('from .eigen_qld import *\n')

sha512 = hashlib.sha512()
src_files = ['eigen_qld/eigen_qld.pyx', 'eigen_qld/c_eigen_qld.pxd', 'eigen_qld/eigen_qld.pxd']
src_files = [ '{}/{}'.format(this_path, f) for f in src_files ]
for f in src_files:
  chunk = 2**16
  with open(f, 'r') as fd:
    while True:
      data = fd.read(chunk)
      if data:
        sha512.update(data.encode('ascii'))
      else:
        break
version_hash = sha512.hexdigest()[:7]

class pkg_config(object):
  def __init__(self):
    self.compile_args = []
    self.include_dirs = [ x for x in '@EQLD_INCLUDE_DIRECTORIES@'.split(';') if len(x) ]
    self.library_dirs = [ x for x in '@EQLD_LINK_FLAGS@'.split(';') if len(x) ]
    self.libraries = ['eigen-qld']
    eqld_location = '@EQLD_LOCATION@'
    self.library_dirs.append(os.path.dirname(eqld_location))
    self.found = True

python_libs = []
python_lib_dirs = []
python_others = []
if not win32_build:
  tokens = subprocess.check_output(['python-config', '--ldflags']).split()
  tokens = [ token.decode('ascii') for token in tokens ]
  for token in tokens:
    flag = token[:2]
    value = token[2:]
    if flag == '-l':
      python_libs.append(value)
    elif flag == '-L':
      python_lib_dirs.append(value)
    elif token[:1] == '-':
      python_others.append(token)

config = pkg_config()

config.compile_args.append('-std=c++11')
for o in python_others:
  config.compile_args.append(o)
config.include_dirs.append(os.getcwd() + "/include")
if not win32_build:
  config.library_dirs.extend(python_lib_dirs)
  config.libraries.extend(python_libs)
else:
  config.compile_args.append("-DWIN32")

def GenExtension(name, pkg, ):
  pyx_src = name.replace('.', '/')
  cpp_src = pyx_src + '.cpp'
  pyx_src = pyx_src + '.pyx'
  ext_src = pyx_src
  if pkg.found:
    return Extension(name, [ext_src], extra_compile_args = pkg.compile_args, include_dirs = pkg.include_dirs + [numpy_get_include()], library_dirs = pkg.library_dirs, libraries = pkg.libraries)
  else:
    print("Failed to find {}".format(pkg.name))
    return None

extensions = [
  GenExtension('eigen_qld.eigen_qld', config)
]

extensions = [ x for x in extensions if x is not None ]
packages = ['eigen_qld']
data = ['__init__.py', 'c_eigen_qld.pxd', 'eigen_qld.pxd']

extensions = cythonize(extensions)

setup(
    name = 'eigen_qld',
    version='1.0.0-{}'.format(version_hash),
    ext_modules = extensions,
    packages = packages,
    package_data = { 'eigen_qld': data }
)

@@ -2084,457 +2084,8 @@
 ue%0A%0A
-python_libs = %5B%5D%0Apython_lib_dirs = %5B%5D%0Apython_others = %5B%5D%0Aif not win32_build:%0A  tokens = subprocess.check_output(%5B'python-config', '--ldflags'%5D).split()%0A  tokens = %5B token.decode('ascii') for token in tokens %5D%0A  for token in tokens:%0A    flag = token%5B:2%5D%0A    value = token%5B2:%5D%0A    if flag == '-l':%0A      python_libs.append(value)%0A    elif flag == '-L':%0A      python_lib_dirs.append(value)%0A    elif token%5B:1%5D == '-':%0A      python_others.append(token)%0A%0A
 conf
@@ -2148,64 +2148,8 @@
 1')%0A
-for o in python_others:%0A  config.compile_args.append(o)%0A
 conf
@@ -2200,20 +2200,16 @@
 de%22)%0Aif 
-not 
 win32_bu
@@ -2217,99 +2217,8 @@
 ld:%0A
-  config.library_dirs.extend(python_lib_dirs)%0A  config.libraries.extend(python_libs)%0Aelse:%0A
   co

Remove python-config call from setup.in.py