# Copyright 2012-2017 CNRS-UM LIRMM, CNRS-AIST JRL
#
# This file is part of Tasks.
#
# Tasks 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.
#
# Tasks 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 Tasks.  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 + '/tasks/__init__.py', 'w') as fd:
    fd.write('from . tasks import *\n')
    fd.write('from . import qp\n')
with open(this_path + '/tasks/qp/__init__.py', 'w') as fd:
    fd.write('from .qp import *\n')

sha512 = hashlib.sha512()
src_files = ['tasks/tasks.pyx', 'tasks/c_tasks.pxd', 'tasks/tasks.pxd']
src_files.extend( ['tasks/qp/qp.pyx', 'tasks/qp/c_qp.pxd', 'tasks/qp/qp.pxd', 'include/qp_wrapper.hpp'] )
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 '@TASKS_INCLUDE_DIRECTORIES@'.split(';') if len(x) ]
    self.library_dirs = [ x for x in '@TASKS_LINK_FLAGS@'.split(';') if len(x) ]
    self.libraries = ['Tasks']
    tasks_location = '@TASKS_LOCATION@'
    self.library_dirs.append(os.path.dirname(tasks_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('tasks.tasks', config),
  GenExtension('tasks.qp.qp', config)
]

extensions = [ x for x in extensions if x is not None ]
packages = ['tasks']
data = ['__init__.py', 'c_tasks.pxd', 'tasks.pxd', 'qp/__init__.py', 'qp/c_qp.pxd', 'qp/qp.pxd']

extensions = cythonize(extensions)

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

@@ -2274,457 +2274,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
@@ -2338,64 +2338,8 @@
 1')%0A
-for o in python_others:%0A  config.compile_args.append(o)%0A
 conf
@@ -2390,20 +2390,16 @@
 de%22)%0Aif 
-not 
 win32_bu
@@ -2407,99 +2407,8 @@
 ld:%0A
-  config.library_dirs.extend(python_lib_dirs)%0A  config.libraries.extend(python_libs)%0Aelse:%0A
   co

Remove python-config call in setup.in.py