#!/usr/bin env python
# -*- coding: utf-8 -*-

#/*##########################################################################
# Copyright (C) 2001-2013 European Synchrotron Radiation Facility
#
#              PyHST2
#  European Synchrotron Radiation Facility, Grenoble,France
#
# PyHST2 is  developed at
# the ESRF by the Scientific Software  staff.
# Principal author for PyHST2: Alessandro Mirone.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# PyHST2 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 General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# PyHST2; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
# Suite 330, Boston, MA 02111-1307, USA.
#
# PyHST2 follows the dual licensing model of Trolltech's Qt and Riverbank's PyQt
# and cannot be used as a free plugin for a non-free program.
#
# Please contact the ESRF industrial unit (industry@esrf.fr) if this license
# is a problem for you.
#############################################################################*/


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function


"""
Installation script:

python setup.py build

"""

__author__ = "Jerome Kieffer"
__contact__ = "Jerome.Kieffer@ESRF.eu"
__license__ = "GPLv2+"
__copyright__ = "European Synchrotron Radiation Facility, Grenoble, France"
__date__ = "28/03/2013"
__satus__ = "development"
import sys, os
import math
import glob
from distutils.core import Extension, setup
# from distutils.command.build_ext import build_ext
from numpy.distutils.misc_util import get_numpy_include_dirs
from os.path import join as pjoin
import string
import stat

if 0:
    from optparse import OptionParser
    parser = OptionParser()
    parser.disable_interspersed_args()
    parser.add_option("--nocuda", action="store_false", dest="DOCUDA", default=True)
    parser.add_option("--onlycuda", action="store_true", dest="ONLYCUDA", default=False)
    (options, args) = parser.parse_args(sys.argv)
    print( args)
    DOCUDA=options.DOCUDA
    ONLYCUDA=options.ONLYCUDA
    if ONLYCUDA==1:
        DOCUDA=1

### DEFAULT
DOCUDA=1
ONLYCUDA=0
DO_LINK=0

### CHANGE HERE
DOCUDA   = 1
ONLYCUDA = 0
DO_LINK  = 0

global version
global aumento_versione
aumento_versione="a"

global version

if DO_LINK==0:
    version = [eval(l.split("=")[1]) for l in open(os.path.join(os.path.dirname(
        os.path.abspath(__file__)), "PyHST", "__init__.py"))
               if l.strip().startswith("version")][0]
else:
    version = "2020c"
    

def do_link():
    global aumento_versione
    global version
    # aumento_versione=""


    version = "2020c"

    packages = []


    package_dir = {'PyHST2_'+version: 'PyHST', 'PyHST2_'+version+'.test': 'PyHST/test', 'PyHST2_'+version+'.third_party': 'PyHST/third_party' }

    script_files = glob.glob('scripts_link/pyhst2')+glob.glob('scripts_link/pyhst2_info')


    description = "Python High Speed Tomography"
    long_description = """
    PyHST is a python program for Tomographic data reconstruction based on direct filtered back-projection algorithm
    """

    distrib = setup(name="pyhst2_links",
                    license="GPL",
                    version=version+aumento_versione,
                    description=description,
                    author="Alessandro Mirone",
                    author_email="mirone@esrf.fr",
                    url="http://forge.epn-campus.eu/projects/pyhst",
                    long_description=long_description,
                    packages=packages,
                    package_dir=package_dir,
                    platforms='any',
                    scripts=script_files,
                    )


def do_link_unstable():
    global aumento_versione
    global version
   #  aumento_versione=""

    version = "2020b"

    packages = []


    package_dir = {'PyHST2_'+version: 'PyHST'}

    script_files = glob.glob('scripts_link/pyhst2_unstable')+glob.glob('scripts_link/pyhst2_unstable_info')


    description = "Python High Speed Tomography"
    long_description = """
    PyHST is a python program for Tomographic data reconstruction based on direct filtered back-projection algorithm
    """

    distrib = setup(name="pyhst2unstable_links",
                    license="GPL",
                    version=version+aumento_versione,
                    description=description,
                    author="Alessandro Mirone",
                    author_email="mirone@esrf.fr",
                    url="http://forge.epn-campus.eu/projects/pyhst",
                    long_description=long_description,
                    packages=packages,
                    package_dir=package_dir,
                    platforms='any',
                    scripts=script_files,
                    )



def do_pyhst():
    global version
    try:
        import numpy
    except ImportError:
        text = "You must have numpy installed.\n"
        text += "See http://sourceforge.net/project/showfiles.php?group_id=1369&package_id=175103\n"
        raise ImportError( text)


    jn = os.sep.join

    mpi_dirs = ["/usr/include/openmpi/"]
    mpilibs_dirs = []

    # mpi_dirs = ["/home/test/packages/include"]
    # mpilibs_dirs = ["/home/test/packages/lib"]

    if 1:
        hdf5_dirs = ["/usr/include/hdf5/serial/"]
        hdf5_lib  = "hdf5_serial"
    else:
        hdf5_dirs = []
        hdf5_lib  = "hdf5"

    ###########################
    ## hdf5 desactivation ( during installation incompatibilities with different versions on the cluster)
    # hdf5_lib = "c"


    
    cmdclass = {}
    ext_modules = []
    internal_clibraries = []


    if not ONLYCUDA:
        packages = ['PyHST2_'+version, 'PyHST2_'+version+'.test', 'PyHST2_'+version+'.third_party']
    else:
        packages = []

    package_dir = {'PyHST2_'+version: 'PyHST'}
    if sys.platform == "win32":
        raise RuntimeError("non sense ")
    else:
        define_macros = []
        if not ONLYCUDA:
            script_files = glob.glob('scripts/*')
        else:
            script_files = []



    def find_in_path(name, path):
        "Find a file in a search path"
        #adapted fom http://code.activestate.com/recipes/52224-find-a-file-given-a-search-path/
        for dirn in path.split(os.pathsep):
            binpath = pjoin(dirn, name)
            if os.path.exists(binpath):
                return os.path.abspath(binpath)
        return None

    def locate_cuda():
        """Locate the CUDA environment on the system

        Returns a dict with keys 'home', 'nvcc', 'include', and 'lib'
        and values giving the absolute path to each directory.

        Starts by looking for the CUDAHOME env variable. If not found, everything
        is based on finding 'nvcc' in the PATH.
        """

        # first check if the CUDAHOME env variable is in use
        if 'CUDAHOME' in os.environ:
            home = os.environ['CUDAHOME']
            nvcc = pjoin(home, 'bin', 'nvcc')
        else:
            # otherwise, search the PATH for NVCC
            nvcc = find_in_path('nvcc', os.environ['PATH'])
            if nvcc is None:
                raise EnvironmentError('The nvcc binary could not be '
                    'located in your $PATH. Either add it to your path, or set $CUDAHOME')
            home = os.path.dirname(os.path.dirname(nvcc))

        cudaconfig = {'home':home, 'nvcc':nvcc,
                      'include': pjoin(home, 'include')}
        lib =  pjoin(home, 'lib')
        if os.path.exists(lib+"64") and    math.log(sys.maxsize)/math.log(2) > 60: ##        sys.maxint == 2**63-1:
            cudaconfig["lib"] = lib+"64"
        elif os.path.exists(lib+"32") and math.log(sys.maxsize)/math.log(2) < 60:
            cudaconfig["lib"] = lib+"32"
        elif os.path.exists(lib):
            cudaconfig["lib"] = lib
        else:
            print(("No cuda library found !!!!"))
        for key, val in cudaconfig.items():
            if not os.path.exists(val):
                raise EnvironmentError('The CUDA %s path could not be located in %s' % (key, val))
        return cudaconfig


    def customize_compiler_for_nvcc(self):
        """inject deep into distutils to customize how the dispatch
        to gcc/nvcc works.

        If you subclass UnixCCompiler, it's not trivial to get your subclass
        injected in, and still have the right customizations (i.e.
        distutils.sysconfig.customize_compiler) run on it. So instead of going
        the OO route, I have this. Note, it's kindof like a wierd functional
        subclassing going on."""

        # tell the compiler it can processes .cu
        self.src_extensions.append('.cu')

        # save references to the default compiler_so and _comple methods
        default_compiler_so = self.compiler_so
        super_comp = self._compile

        # now redefine the _compile method. This gets executed for each
        # object but distutils doesn't have the ability to change compilers
        # based on source extension: we add it.
        def _compile(obj, src, ext, cc_args, extra_postargs, pp_opts):
            if os.path.splitext(src)[1] == '.cu':
                # use the cuda for .cu files
                self.set_executable('compiler_so', CUDA['nvcc'])
                # use only a subset of the extra_postargs, which are 1-1 translated
                # from the extra_compile_args in the Extension class

                
                postargs = extra_postargs['nvcc']

                if "USECLANG4NVCC" in os.environ and os.environ ["USECLANG4NVCC"]=="YES":
                    postargs = postargs + [" -ccbin clang-3.8"]
            else:
                print(" EXTRA ", extra_postargs)
                self.set_executable('compiler_so', "mpicc")
                postargs = extra_postargs['gcc']
                # postargs = extra_postargs['gcc']

            super_comp(obj, src, ext, cc_args, postargs, pp_opts)
            # reset the default compiler_so, which we might have changed for cuda
            self.compiler_so = default_compiler_so

        # inject our redefined _compile method into the class
        self._compile = _compile



    try:
        from Cython.Distutils import build_ext, Extension
        CYTHON = True
    except ImportError:
        CYTHON = False

    if CYTHON:
        cython_c_ext = ".pyx"
    else:
        cython_c_ext = ".cpp"
        from distutils.command.build_ext import build_ext, Extension


    # We subclass the build_ext class in order to handle compiler flags
    # for openmp and opencl etc in a cross platform way
    translator = {
            # Compiler
                # name, compileflag, linkflag
            'msvc' : {
                'openmp' : ('/openmp', ' '),
                'debug'  : ('/Zi', ' '),
                'OpenCL' : 'OpenCL',
                },
            'mingw32':{
                'openmp' : ('-fopenmp', '-fopenmp'),
                'debug'  : ('-g', '-g'),
                'stdc++' : 'stdc++',
                'OpenCL' : 'OpenCL'
                },
            'default':{
                'openmp' : ('-fopenmp', '-fopenmp'),
                'debug'  : ('-g', '-g'),
                'stdc++' : 'stdc++',
                'OpenCL' : 'OpenCL'
                }
            }

    cmdclass = {}

    class build_ext_tds2el(build_ext):
        def build_extensions(self):

            customize_compiler_for_nvcc(self.compiler)


            # print( self.compiler.compiler_type)

            if self.compiler.compiler_type in translator:
                trans = translator[self.compiler.compiler_type]
            else:
                trans = translator['default']


            for e in self.extensions:
                e.extra_compile_args = [ trans[a][0] if a in trans else a
                                        for a in e.extra_compile_args]
                e.extra_link_args = [ trans[a][1] if a in trans else a
                                     for a in e.extra_link_args]

                if    e.libraries !=[ "fftw3f"] and e.libraries !=[ "mpi"]:
                    e.libraries = filter(None, [ trans[a] if a in trans else None
                                                 for a in e.libraries])

                # If you are confused look here:
                # print( e, e.libraries)
                # print( e.extra_compile_args)
                # print( e.extra_link_args)
            build_ext.build_extensions(self)

    # cmdclass['build_ext'] = build_ext_tds2el


    # run the customize_compiler
    class custom_build_ext(build_ext):
        """
        Cuda aware builder with nvcc compiler support
        """
        def build_extensions(self):
            customize_compiler_for_nvcc(self.compiler)
            build_ext.build_extensions(self)

    cmdclass['build_ext'] = custom_build_ext

    CUDA={'include':[""]}
    if  DOCUDA:
        CUDA={'include':[]}
        CUDA .update(locate_cuda())

        CUDA["arch"] = [  #  "-gencode", "arch=compute_20,code=compute_20",
                           "-gencode", "arch=compute_30,code=compute_30" ,
                           "-gencode", "arch=compute_50,code=compute_50"
                       ]

        # print( CUDA)
        
        CUDA["Xptxas"] = [" ", " -Xptxas=-v"]

    def build_Cspace():
        """
        Define how to build the main Cspace C extension

        @return: module
        """
        global version
        if sys.platform == "win32" :
            raise RuntimeError("non-sense ")
    #    else:
    #        sdk_libs = ['gcc', 'm']

        c_sorgenti_tmp = ["CCspace.c", "cpyutils.c", "Cspace.c"  , "edftools.c" , "cpu_main.c", "pyhst_nnfbp.c" ]#, "PyHST/Cspace/h5tools.c" ]
        c_sorgenti = [jn(['PyHST', 'Cspace', tok]) for tok in c_sorgenti_tmp]

        depends_tmp = [ "CCspace.h", "cpyutils.h", "edftools.h"]
        depends = [jn(['PyHST', 'Cspace', tok]) for tok in depends_tmp]
        depends = []


        module = Extension(name='PyHST2_'+version+'.Cspace',
                           sources=c_sorgenti ,
                           depends=depends,
                           library_dirs= mpilibs_dirs,
                           libraries=["fftw3f_threads", "fftw3f",hdf5_lib, "mpi"],
                           extra_link_args=['-fopenmp'] ,
                           extra_compile_args={'gcc': ["-fPIC",'-fopenmp',"-g" ,"-std=c99","-Wall"]},
                           define_macros=define_macros,
                           include_dirs=[ CUDA['include'], numpy.get_include()] + mpi_dirs + hdf5_dirs )
        return module



    def build_gputomo():
        """
        Build the GPU tomo C module

        @return: module

        """
        global version

        sources = ["src/wt.cu", "src/common.cu", "src/utils.cu", "src/separable.cu", "src/nonseparable.cu", "src/haar.cu", "src/filters.cpp"]
        sources = [jn(['PyHST', 'Cspace', 'pdwt', tok]) for tok in sources]
        sources.extend(["PyHST/Cspace/gputomo.cu", "PyHST/Cspace/cudamedianfilter.cu","PyHST/Cspace/chambollepock.cu", "PyHST/Cspace/wavelets.cu", "PyHST/Cspace/sinofilters.cu"])

        module = Extension('PyHST2_'+version+'/libgputomo',
                    sources=sources,
                    library_dirs=[CUDA['lib']],
                    libraries=['cudart', "cublas", "cuda", "cufft", hdf5_lib],
                    runtime_library_dirs=[CUDA['lib']],
                    # this syntax is specific to this build system
                    # we're only going to use certain compiler args with nvcc and not with gcc
                    # the implementation of this trick is in customize_compiler() below
                    extra_compile_args={'gcc': ["-std=c99", "-g","-fPIC", "-O3","-Wall"],
                                        'nvcc': CUDA["arch"] + [ "--compiler-options",  "-fPIC", "-O3", "-g","-D_FORCE_INLINES" ]},
                    include_dirs=[numpy.get_include(), CUDA['include'], 'PyHST/Cspace'] + hdf5_dirs)
        return module

    def build_gpuunsharp():
        """
        Build the GPU tomo C module

        @return: module

        """
        global version

        sources = ["PyHST/Cspace/unsharp3D.c" , "PyHST/Cspace/cudaunsharp.cu","PyHST/Cspace/cpyutils.c" ]


        module = Extension(name='PyHST2_'+version+'.unsharp3D',
                           sources=sources ,
                           depends=[],
                           library_dirs=[CUDA['lib']],
                           libraries=['cudart','QtGui','QtCore','cudart','tiff'],
                           
                           runtime_library_dirs=[CUDA['lib']],
                           
                           extra_compile_args={'gcc': ["-std=c99","-g","-fPIC", "-O3","-Wall"],
                                               'nvcc': CUDA["arch"] + [ "--compiler-options",  "-fPIC", "-O3", "-g","-D_FORCE_INLINES" ]},
                           include_dirs=[numpy.get_include(), CUDA['include'], 'PyHST/Cspace',"/usr/include/qt4"] )


        return module


    def build_projection():
        """
        Build the GPU tomo C module

        @return: module

        """
        global version
        module = Extension('PyHST2_'+version+'/libprojection',
                               sources=["PyHST/Cspace/c_hst_project_1over.cu"],
                               library_dirs=[CUDA['lib']],
                               libraries=['cudart', "cuda", "cufft"],
                               runtime_library_dirs=[CUDA['lib']],
                               extra_compile_args={'gcc': ["-fPIC", "-O3"],
                                                   'nvcc': CUDA["arch"] + ["--compiler-options", "-fPIC,-O3" ,"-D_FORCE_INLINES"]},
                               include_dirs=[numpy.get_include(), CUDA['include'], 'PyHST/Cspace']+ hdf5_dirs)
        return module


    '''
    # Too complicated to build several cuda module, and then to link *and* use the dlopen mechanism
    def build_wavelets():
        """
        Build the Wavelets tomo C module, based on pywt

        @return: module
        """
        global version
        sources = ["src/wt.cu", "src/common.cu", "src/utils.cu", "src/separable.cu", "src/nonseparable.cu", "src/haar.cu", "src/filters.cpp"]
        sources = [jn(['PyHST', 'Cspace', 'pdwt', tok]) for tok in sources]
        #sources.extend(["PyHST/Cspace/wavelets.cu", "PyHST/Cspace/sinofilters.cu"])

        module = Extension('PyHST2_'+version+'/libwavelets',
                               sources=sources,
                               library_dirs=[CUDA['lib']],
                               libraries=["cudart", "cuda", "cublas"],
                               runtime_library_dirs=[CUDA['lib']],
                               extra_compile_args={'gcc': ["-fPIC", "-O3"],
                                                   'nvcc': CUDA["arch"] + ["--compiler-options", "-fPIC,-O3" ,"-D_FORCE_INLINES"]},
                               include_dirs=[numpy.get_include(), CUDA['include'], 'PyHST/Cspace'])
        return module
    '''



    def build_segmentation():

        global version

        c_sorgenti_tmp = ["segment_cy"+cython_c_ext, "segment.cc"]
        # c_sorgenti_tmp = ["segment_cy"+cython_c_ext]
        c_sorgenti = [jn(['PyHST', 'segment',  tok]) for tok in c_sorgenti_tmp]

        depends_tmp = [ "segment.h"]
        depends = [jn(['PyHST', 'segment',  tok]) for tok in depends_tmp]

        if sys.version_info > (3, 0):
            cython_ext2 = Extension(
                'PyHST2_'+version+'.segment_cy',
                sources=c_sorgenti,
                depends=depends,
                library_dirs =      mpilibs_dirs,
                libraries=[ "mpi"],
                include_dirs=get_numpy_include_dirs()+ mpi_dirs+[],
                language="c++",             # generate C++ code
                extra_compile_args={'gcc':['-fopenmp',"-fPIC", "-O3"] },
                extra_link_args=['-fopenmp'] ,
                cython_directives={'language_level' : "3"}
            )
        else:
            cython_ext2 = Extension(
                'PyHST2_'+version+'.segment_cy',
                sources=c_sorgenti,
                depends=depends,
                library_dirs =      mpilibs_dirs,
                libraries=[ "mpi"],
                include_dirs=get_numpy_include_dirs()+ mpi_dirs+[],
                language="c++",             # generate C++ code
                extra_compile_args={'gcc':['-fopenmp',"-fPIC", "-O3"] },
                extra_link_args=['-fopenmp'] ,
            )
            
        return cython_ext2

    #############################################################################

# extensions = cythonize(extensions, compiler_directives={'language_level' : "3"})) # or "2" or "3str"


    ###########################################################################################################
    from distutils.command.install_scripts import install_scripts
    class smart_install_scripts(install_scripts):
        def run (self):
            global  version

            install_cmd = self.get_finalized_command('install')
            self.install_dir = getattr(install_cmd, 'install_scripts')
            self.install_lib_dir = getattr(install_cmd, 'install_lib')

            self.outfiles = []
            for filein in glob.glob('scripts/*'):
                if filein in glob.glob('scripts/*~'): continue

                print( "INSTALLO ", filein)

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

                filedest = os.path.join(self.install_dir, os.path.basename(filein+"2_"+version))
                print( os.path.basename(filein+"2_"+version))
                print( filedest)

                if os.path.exists(filedest):
                    os.remove(filedest)

                text = open(filein, 'r').read()
                text=text.replace("import PyHST", "import PyHST2_"+version) 
                text=text.replace("python", sys.executable)                 

                f=open(filedest, 'w')
                f.write(text)
                f.close()
                self.outfiles.append(filedest)

            if os.name == 'posix':
                # Set the executable bits (owner, group, and world) on
                # all the scripts we just installed.
                for file in self.get_outputs():
                    if self.dry_run:
                        pass
                    else:
                        mode = ((os.stat(file)[stat.ST_MODE]) | 0o555) & 0o7777
                        os.chmod(file, mode)


    #############################################################################################################

    cmdclass['install_scripts'] = smart_install_scripts


    if not ONLYCUDA:
        ext_modules.append(build_Cspace())
        ext_modules.append(build_segmentation())
    if DOCUDA:
        ext_modules.append(build_gputomo())
        # ext_modules.append(build_gpuunsharp())
        ext_modules.append(build_projection())
        #ext_modules.append(build_wavelets())


    #######################
    # build_doc commandes #
    #######################

    try:
        import sphinx
        import sphinx.util.console
        sphinx.util.console.color_terminal = lambda: False
        from sphinx.setup_command import BuildDoc
    except ImportError:
        sphinx = None

    if sphinx:
        class build_doc(BuildDoc):

            def run(self):
                # make sure the python path is pointing to the newly built
                # code so that the documentation is built on this and not a
                # previously installed version

                build = self.get_finalized_command('build')
                sys.path.insert(0, os.path.abspath(build.build_lib))
                # we need to reload PyMca from the build directory and not
                # the one from the source directory which does not contain
                # the extensions
                BuildDoc.run(self)
                sys.path.pop(0)
        cmdclass['build_doc'] = build_doc


    description = "Python High Speed Tomography"
    long_description = """
    PyHST is a python program for Tomographic data reconstruction based on direct filtered back-projection algorithm
    """


    post_fix=""
    if DOCUDA==0 and ONLYCUDA==0:
        post_fix="_base"
    elif  DOCUDA==1 and ONLYCUDA==1:
        post_fix="_cudaextensions"

    distrib = setup(name="PyHST2_"+version+post_fix,
                    license="GPL",
                    version=version+aumento_versione, ## aumenta qua versione
                    description=description,
                    author="Alessandro Mirone",
                    author_email="mirone@esrf.fr",
                    url="http://forge.epn-campus.fr/projects/PyHST",
                    long_description=long_description,
                    packages=packages,
                    package_dir=package_dir,
                    platforms='any',
                    ext_modules=ext_modules,
                    cmdclass=cmdclass ,
                    scripts=script_files
                    )




if DO_LINK:
    if DO_LINK==1:
        do_link()
    else: 
        do_link_unstable()
       
else:
    do_pyhst()









# What you basically need to do is to override the build_ext command class in your setup.py and register it in the command classes. In your custom impl of build_ext, configure and call cmake to configure and then build the extension modules. Unfortunately, the official docs are rather laconic about how to implement custom distutils commands (see Extending Distutils); I find it much more helpful to study the commands code directly. For example, here is the source code for the build_ext command.
# Example project

# I have prepared a simple project consisting out of a single C extension foo and a python module spam.eggs:

# so-42585210/
# ├── spam
# │   ├── __init__.py  # empty
# │   ├── eggs.py
# │   ├── foo.c
# │   └── foo.h
# ├── CMakeLists.txt
# └── setup.py

# Files for testing the setup

# These are just some simple stubs I wrote to test the setup script.

# spam/eggs.py (only for testing the library calls):

# from ctypes import cdll
# import pathlib


# def wrap_bar():
#     foo = cdll.LoadLibrary(str(pathlib.Path(__file__).with_name('libfoo.dylib')))
#     return foo.bar()

# spam/foo.c:

# #include "foo.h"

# int bar() {
#     return 42;
# }

# spam/foo.h:

# #ifndef __FOO_H__
# #define __FOO_H__

# int bar();

# #endif

# CMakeLists.txt:

# cmake_minimum_required(VERSION 3.10.1)
# project(spam)
# set(src "spam")
# set(foo_src "spam/foo.c")
# add_library(foo SHARED ${foo_src})

# Setup script

# This is where the magic happens. Of course, there is a lot of room for improvements - you could pass additional options to CMakeExtension class if you need to (for more info on the extensions, see Building C and C++ Extensions), make the CMake options configurable via setup.cfg by overriding methods initialize_options and finalize_options etc.

# import os
# import pathlib

# from setuptools import setup, Extension
# from setuptools.command.build_ext import build_ext as build_ext_orig


# class CMakeExtension(Extension):

#     def __init__(self, name):
#         # don't invoke the original build_ext for this special extension
#         super().__init__(name, sources=[])


# class build_ext(build_ext_orig):

#     def run(self):
#         for ext in self.extensions:
#             self.build_cmake(ext)
#         super().run()

#     def build_cmake(self, ext):
#         cwd = pathlib.Path().absolute()

#         # these dirs will be created in build_py, so if you don't have
#         # any python sources to bundle, the dirs will be missing
#         build_temp = pathlib.Path(self.build_temp)
#         build_temp.mkdir(parents=True, exist_ok=True)
#         extdir = pathlib.Path(self.get_ext_fullpath(ext.name))
#         extdir.mkdir(parents=True, exist_ok=True)

#         # example of cmake args
#         config = 'Debug' if self.debug else 'Release'
#         cmake_args = [
#             '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + str(extdir.parent.absolute()),
#             '-DCMAKE_BUILD_TYPE=' + config
#         ]

#         # example of build args
#         build_args = [
#             '--config', config,
#             '--', '-j4'
#         ]

#         os.chdir(str(build_temp))
#         self.spawn(['cmake', str(cwd)] + cmake_args)
#         if not self.dry_run:
#             self.spawn(['cmake', '--build', '.'] + build_args)
#         os.chdir(str(cwd))


# setup(
#     name='spam',
#     version='0.1',
#     packages=['spam'],
#     ext_modules=[CMakeExtension('spam/foo')],
#     cmdclass={
#         'build_ext': build_ext,
#     }
# )

# Testing

# Build the project's wheel, install it. Test the library is installed:

# $ pip show -f spam
# Name: spam
# Version: 0.1
# Summary: UNKNOWN
# Home-page: UNKNOWN
# Author: UNKNOWN
# Author-email: UNKNOWN
# License: UNKNOWN
# Location: /Users/hoefling/.virtualenvs/stackoverflow/lib/python3.6/site-packages
# Requires: 
# Files:
#   spam-0.1.dist-info/DESCRIPTION.rst
#   spam-0.1.dist-info/INSTALLER
#   spam-0.1.dist-info/METADATA
#   spam-0.1.dist-info/RECORD
#   spam-0.1.dist-info/WHEEL
#   spam-0.1.dist-info/metadata.json
#   spam-0.1.dist-info/top_level.txt
#   spam/__init__.py
#   spam/__pycache__/__init__.cpython-36.pyc
#   spam/__pycache__/eggs.cpython-36.pyc
#   spam/eggs.py
#   spam/libfoo.dylib

# Run the wrapper function from spam.eggs module:

# $ python -c "from spam import eggs; print(eggs.wrap_bar())"
# 42









