# setup.py is used with Distutils for building isocontouring library
# the "build" command builds the C++ library libisocontour.a
# and the python extension _isocontour.so

import sys, os
from os import path
from distutils.core import setup, Extension
from distutils.command.build_clib import build_clib
from distutils.command.build import build
from distutils.command.install_data import install_data
from distutils.command.sdist import sdist

pack_name = "UTpackages.UTisocontour"
ext_name = "_isocontour"
platform = sys.platform

# Lists of include dirs, pre-processor macros, libraries at link-time
# (build_ext).
import numpy
numpy_include =  numpy.get_include()

incl_dir = [path.join(".", "src"), numpy_include]
lib_dir = path.join(".", "lib", platform)
macros = [("SP2", None), ("_BOOL", None), ("USEDICT", None)]
comp_args = []
link_args = []
libs = []
if platform == "sunos5":
    #libs = ["contour", "Crun", "Cstd"]
    libs = ["Crun", "Cstd"] # 'contour' will be included by build_ext command 
    #comp_args.extend(['-Kpic', '-mt'])
    macros = [("SP2", None), ("USEDICT", None)]
elif platform == "win32":
    comp_args.append("/MT")
    macros.append(("WIN32", None))

elif platform == "irix6":
    libs = ["C",]
    comp_args.append( "-LANG:std" )
    link_args.append( "-LANG:std" )
    
elif platform == "linux2":
    macros.append(("_LITTLE_ENDIAN", None))

elif platform == "darwin":
    macros.append(("MACOS_X", None))

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

if platform == "linux2" or platform == "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


# 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):
        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 command build_clib with a derived "modified_build_clib" class
# to use 'CC' for building static C++ library on irix platform
# (instead of 'ar').

class modified_build_clib(build_clib):

    def build_libraries(self, libraries):
        if sys.platform == "irix6":
            self.compiler.archiver = ['CC', '-ar', '-o']
        build_clib.build_libraries(self, libraries)


# Change the order of commands that are called by "build"
# so that 'build_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 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)
    

# List of source files - to build C lib (build_clib).
src_list = ["contour.cpp", "edgehash.cpp", "cellqueue.cpp", "range.cpp",
            "seedcells.cpp", "data.cpp", "dataslc.cpp", "datavol.cpp",
            "segtree.cpp", "contour2d.cpp", "contour3d.cpp",
            "conplot_p.cpp", "conplot.cpp", "conplot2d.cpp", "queue.cpp",
            "squeue.cpp", "rangeprop.cpp", "conplot3d.cpp",
            "rangesweep.cpp", "datareg2.cpp", "conplotreg2.cpp",
            "dirseeds.cpp", "inttree.cpp", "bucketsearch.cpp",
            "datareg3.cpp", "conplotreg3.cpp", "regprop.cpp",
            "dirseedsreg2.cpp", "regprop2.cpp", "seedchkr2.cpp",
            "seedchkr3.cpp", "seedall.cpp", "respprop2.cpp",
            "seeddirreg3.cpp", "cubes.cpp", "dict.c"]
for i in range(len(src_list)):
    src_list[i] = path.join(".", "src", src_list[i] )
src_list.append(path.join("UTisocontour", "isocontour.i"))
#print "sorce list:" ,src_list

data_files = [( path.join("UTisocontour", "Tests"),
                [path.join("UTisocontour", "Tests", "1ak3.C.map"),
                 path.join("UTisocontour", "Tests", "pot-2eti-glucose-3fields.raw")] )]

# the setup() does all the work:
dist = setup(name = pack_name, #version="?",
             description = "Isocontour library extension module",
             author = "Molecular Graphics Laboratory",
             author_email = "mgltools@scripps.edu",
             url = "http://www.scripps.edu/~sanner/python/packager.html",
             packages = [pack_name, pack_name+".Tests"],
             package_dir = {pack_name: "UTisocontour"},
             ext_package = pack_name,
             # use the derived command classes:
             data_files = data_files,
             cmdclass = {"build_clib" : modified_build_clib,
                         "build" : modified_build,
                         "install_data" : modified_install_data,
                         "sdist" : modified_sdist}, 
             ## libraries = [('contour',
##                            {'sources': src_list,
##                             'macros': macros,
##                             'include_dirs': incl_dir,
##                             #'library_dirs': library_dirs,
##                             #'extra_compile_args': # comp_args doesn't work
##                             } ),] ,
             ext_modules = [Extension (ext_name, src_list,
                                    #[path.join("UTisocontour", "isocontour.i")],
                            include_dirs = incl_dir,
                            define_macros = macros,
                            #library_dirs = [lib_dir],
                            libraries = libs,
                            extra_compile_args = comp_args,
                            extra_link_args = link_args       
                     ) ] ,)

# cp built .so from ./build/lib.platform to ./pack_name/ - for testing.
##  from distutils.util import get_platform
##  from distutils.file_util import copy_file

##  plat_specifier = ".%s-%s" % (get_platform(), sys.version[0:3])
##  orig_ext = path.join(".", "build", "lib"+plat_specifier , pack_name, ext_name+".so")
##  cp_ext = path.join(pack_name, ext_name+".so")
##  if path.isfile(orig_ext):
##      copy_file(orig_ext, cp_ext, update=1)
##  else:
##      print "file %s does not exist" % (orig_ext,)

