import setuptools
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
import os, subprocess

# sources+tests
os.sys.path.append("@PROJECT_SOURCE_DIR@")

class CMakeExtension(Extension):
  def __init__(self, name, sourcedir=''):
    Extension.__init__(self, name, sources=[])
    self.sourcedir = os.path.abspath(sourcedir)


class CMakeBuild(build_ext):
  def run(self):
    for ext in self.extensions:
      self.build_extension(ext)

  def build_extension(self, ext):

    ext_fullpath = self.get_ext_fullpath(ext.name)
    ext_basename = os.path.basename(ext_fullpath)
    ext_dirname = os.path.dirname(ext_fullpath)
    project_binary_dir = "@PROJECT_BINARY_DIR@"

    if not os.path.exists(self.build_temp):
      os.makedirs(self.build_temp)

    cfg = 'Debug' if self.debug else 'Release'
    build_args = ['--config', cfg]
    subprocess.check_call(
      ['cmake', '--build', "@CMAKE_BINARY_DIR@", '--target', 'libint2-python'] + build_args,
      #cwd=self.build_temp
    )

    if not os.path.exists(ext_dirname):
      os.makedirs(ext_dirname)
    self.copy_file(
      os.path.join(project_binary_dir, ext_basename),
      ext_fullpath
    )

    print()  # Add an empty line for cleaner output

setup(
  name = 'libint2',
  version = '@LIBINT_VERSION@',
  description = 'libint2',
  #packages=['libint2'],
  #package_dir={'': 'src'},
  ext_modules = [ CMakeExtension("libint2") ],
  cmdclass=dict(build_ext=CMakeBuild),
  test_suite='tests',
)
