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

### This file contains Distutil setup() for building 
### _UTVolumeLibrary.so - opengl based volume rendering library developed at Univ. of Texas;

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

from distutils.core import setup, Extension
from distutils.command.sdist import sdist
from distutils.command.install_data import install_data
from distutils.command.install_lib import install_lib
from distutils.command.install import install
from distutils.command.build import build
from distutils.command.bdist_dumb import bdist_dumb
from glob import glob
import os, sys
from os import path

platform = sys.platform

                       
#  HACK: replace cc with CC (gcc with g++)
CC_exe = 'CC'
cc_exe = 'cc'

if platform in ("linux2", "darwin"):
    CC_exe = 'g++'
    cc_exe = 'gcc'
from distutils import sysconfig
save_init_posix = sysconfig._init_posix

def my_init_posix():
    save_init_posix()
    g = sysconfig._config_vars
    for n,r in [('LDSHARED',CC_exe),('CC',CC_exe)]:
        if g[n][:3] == cc_exe:
            print 'my_init_posix: changing %s = %r'%(n,g[n]),
            g[n] = r+g[n][3:]
            print 'to',`g[n]`
if platform in ('sunos5', 'linux2', 'irix6', 'darwin'):
    sysconfig._init_posix = my_init_posix

# Change the order of commands that are called by "build"
# so that 'byuld_py' comes after 'build_ext'. In this case
# 'build_py' will install python modules generated by
# 'build_ext'.

class modified_build(build):

    sub_commands = [('build_clib',    build.has_c_libraries),
                    ('build_ext',     build.has_ext_modules),
                    ('build_py',      build.has_pure_modules),
                    ('build_scripts', build.has_scripts),
                    ]

# Overwrite the prune_file_list method of sdist to not
# remove automatically the RCS/CVS directory from the distribution.


class modified_sdist(sdist):
    def prune_file_list(self):
        """
        Prune off branches that might slip into the file list as created
        by 'read_template()', but really don't belong there:
          * the build tree (typically 'build')
          * the release tree itself (only an issue if we ran 'sdist
            previously with --keep-temp, or it aborted)
        """
        build = self.get_finalized_command('build')
        base_dir = self.distribution.get_fullname()
        self.filelist.exclude_pattern(None, prefix=build.build_base)
        self.filelist.exclude_pattern(None, prefix=base_dir)


# Overwrite the run method of the install_data to install the data files
# in the package.
class modified_install_data(install_data):

    def run(self):
        install_cmd = self.get_finalized_command('install')
        self.install_dir = getattr(install_cmd, 'install_lib')+"UTpackages"
        #print "install_dir", self.install_dir
        return install_data.run(self)
    

packFullName = "UTpackages.UTvolrend"
packName = "UTvolrend"

# List of the python packages to be included in this distribution.
# sdist does not go recursively into subpackages so they need to be
# explicitly listed.
# From these packages only the python modules will be taken
packages = [packFullName, packFullName+".Tests"]

# List of the other (not python) files included in the distribution .
# MANIFEST.in lists these files, so they are included in the distribution.

data_files = [( path.join(packName, 'Tests'),
                [ path.join(packName, 'Tests', 'ct_head.rawiv'),
                path.join(packName, 'Tests', 'colormap.map') ] ) ]

# libVolume.a
source_files = ["ClipCube.cpp", "Extent.cpp", "FragmentProgramARBImpl.cpp",
                "FragmentProgramImpl.cpp", "MyExtensions.cpp",
                "PalettedImpl.cpp", "Plane.cpp", "Polygon.cpp",
                "PolygonArray.cpp", "Renderer.cpp", "RendererBase.cpp",
                "RGBABase.cpp", "SGIColorTableImpl.cpp",
                "SimpleRGBAImpl.cpp", "UnshadedBase.cpp",
                "VolumeRenderer.cpp", "VolumeRendererFactory.cpp",
                "SimpleRGBA2DImpl.cpp", "Paletted2DImpl.cpp"]
for i in range(len(source_files)):
    source_files[i] = path.join("src", source_files[i])
source_files.append(path.join(packName, "utvollib.i"))
import numpy
numpy_include =  numpy.get_include()
source_include = ["src", numpy_include]
source_macros = []
if platform == "darwin":
    source_macros = [("__APPLE__", None)]
    source_include.append("/System/Library/Frameworks/OpenGL.framework/Headers")
elif platform in ["sunos5", "irix6"]:
    source_macros = [("UNIX", None)]
elif platform == "win32":
    source_macros = [("WIN32", None)]

# describe the extensions:
extensions = []
    
# _UTVolumeLibrary.so 

#utlibraries = ["GL"] # libVolume is included automatically
utlibraries = {'posix': ['GL'], 'nt': ['OPENGL32']}.get( os.name, [])
utlibdirs = []
utcflags = []
utmacros = []
#utincludedirs = ["src"]
utincludedirs = source_include
if platform in ('sunos5', 'irix6'):
    utlibraries.append({'sunos5':'Crun', 'irix6':'C'}.get(platform))
    utmacros.append(('UNIX', None))
elif platform == 'darwin':
    utlibdirs.append('/opt/X11/lib')
    utincludedirs.append('/opt/X11/include')
    utmacros.append(('__APPLE__', None))
elif platform == "win32":
    utmacros.append(('WIN32', None))
    
utcflags = {'sunos5':['-Kpic', '-mt'] }.get(platform, [])
extra_link_args = []
if platform == "darwin":
    (osname, host, release, version, machine) = os.uname()
    if release[0]== '9': # leopard
        extra_link_args=['-Wl,-dylib_file,/System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries/libGL.dylib:/System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries/libGL.dylib']

        
utvollib_ext = Extension (
    "_UTVolumeLibrary",
    source_files, #[path.join(packName, "utvollib.i"),],
    include_dirs = utincludedirs,
    define_macros = utmacros,
    library_dirs = utlibdirs,
    libraries = utlibraries,
    extra_compile_args = utcflags,
    extra_link_args = extra_link_args )
extensions.append(utvollib_ext)

# description of what is going to be included in the distribution and
# installed.
dist = setup (name = packFullName,
              version = '1.0',
              description = "Volume Rendering Library python package",
              author = 'Molecular Graphics Laboratory',
              author_email = 'mgltools@scripps.edu',
              download_url = 'http://www.scripps.edu/~sanner/software/packager.html',
              url = 'http://www.scripps.edu/~sanner/software/index.html',
              packages = packages,
              package_dir = {packFullName: packName},
              data_files = data_files,
##               libraries = [('Volume',
##                            {'sources': source_files,
##                             'macros': source_macros,
##                             'include_dirs': source_include,
##                             } ),] ,
              ext_modules = extensions,
              ext_package = packFullName,
              cmdclass = {'sdist': modified_sdist,
                          'install_data': modified_install_data,
                          'build': modified_build,
                          },
              )
