import os, sys
import os.path
import distutils.sysconfig
import modules

platform = str(Platform())

if platform == 'win32':
    boost_root_default = 'Q:\\opt'
    osg_root_default = 'Q:\\opt'
else:
    boost_root_default = '/tmp'         # Point it out of the way jbw
    osg_root_default = '/tmp'           # Point it out of the way jbw

install_dir =  ARGUMENTS.get('install', 'build')

osg_root_default = os.environ.get('OSG_ROOT', osg_root_default)
boost_root_default = os.environ.get('BOOST_ROOT', boost_root_default)

build_opt =  os.environ.has_key('BUILD_OPT')
build_debug = os.environ.has_key('BUILD_DEBUG')
build_framework = os.environ.has_key('BUILD_FRAMEWORK')

build_framework = False  # Override environment jbw

SetOption('implicit_cache', 1)

opts = Options('PyOSG_options.py')

opts.Add(PathOption('OSG_PATH', 'Path to OpenSceneGraph.', osg_root_default))
opts.Add(PathOption('BOOST_PATH', 'Path to Boost Library.', boost_root_default))
opts.Add(BoolOption('DEBUG', 'Whether to compile a debug library', build_debug))
opts.Add(BoolOption('OPT', 'Whether to compile a -O3 library', build_opt))
opts.Add(BoolOption('FRAMEWORK', 'Whether to use the framework version of OpenScenegraph on Mac OSX', build_framework))

env = Environment(ENV = os.environ,
                  options = opts,
                  tools=['default'])

Help(opts.GenerateHelpText(env))


env.Append(CPPPATH = [distutils.sysconfig.get_python_inc(),
                     os.path.join('$OSG_PATH', 'include'),
                     '$BOOST_PATH',
                     'include'])

env.Append(LINKFLAGS =  distutils.sysconfig.get_config_vars().get('LINKFORSHARED', '').split())
env.Append(LIBPATH =    [os.path.join('$OSG_PATH', 'lib')])
env.Append(CPPDEFINES = ['BOOST_PYTHON_DYNAMIC_LIB'])

if platform == 'win32':
    env.Append(CPPDEFINES = ['WIN32', "_CONSOLE"])
    env.Append(CCFLAGS =    ["/Gd", "/GF", "/FD", "/Gy", "/GR", "/EHa", "/Gs", "/MD", "/FD", "/Ogity", "/Zc:forScope", "/Zc:wchar_t", "/Zm800"])
    env.Append(LIBPATH = sys.exec_prefix + os.sep + 'libs')
    OPENGL = 'OpenGL32'
    OPENTHREADS = 'OpenThreadsWin32'
else:
    home = os.environ['HOME']
#    env.Append(CPPFLAGS = ['-Wall', '-ansi']) # jbw is -ansi really needed?
    env.Append(CPPFLAGS = ['-Wall'])

    if platform == 'darwin':
        env.Append(CPPDEFINES = ['__DARWIN_OSX__'])
        if env['FRAMEWORK']:
            print "Building FRAMEWORK version"
            env.Append(CPPFLAGS =   ['-fPIC', '-no-cpp-precomp', '-finline-functions', '-Wno-long-double', '-F/System/Library/Frameworks', '-ftemplate-depth-256'])
            env.Append(CPPDEFINES = ['__USE_OSX_IMPLEMENTATION__'])
            env.Append(CPPDEFINES = ['__USE_OSX_AGL_IMPLEMENTATION__'])
            env.Append(CPPFLAGS =   ["-F" + home + "/Library/Frameworks"])
            env.Append(LINKFLAGS =  ["-F" + home + "/Library/Frameworks"])
            OPENGL = ''
        else:
            print "Building dyld version"
            # from running running bjam "-sTOOLS=darwin" -ofoo
            env.Append(CPPFLAGS = ['-ftemplate-depth-256',
                                   '-DBOOST_PYTHON_DYNAMIC_LIB',
                                   '-Wno-long-double',
                                   '-no-cpp-precomp',
                                   '-fno-inline',
                                   '-fPIC',
#                                   '-fcoalesce-templates', # 10.3.x
                                   '-F/System/Library/Frameworks'])
            env.Append(CPPDEFINES = ['__USE_OSX_IMPLEMENTATION__'])
            env.Append(CPPDEFINES = ['__USE_OSX_AGL_IMPLEMENTATION__'])
            env.Append(LIBPATH = ['/usr/X11R6/lib'])
            OPENGL = ''
    else:
        OPENGL = 'GL'
    OPENTHREADS = 'OpenThreads'

#
# Only needed on 10.3.x
#

if platform == 'darwin':
    if os.environ.has_key('VERSION'):
        OS_VERSION = os.environ['VERSION']
    else:
        OS_VERSION = None

    if OS_VERSION == "powerpc-apple-darwin7.9.0":    
        env.Append(CPPFLAGS = "-DBOOST_PYTHON_TYPE_ID_NAME") # jbw hack

if sys.platform == 'linux2':

    def onUbuntu():
        if not os.path.exists('/etc/issue'):
            return False

        f = open('/etc/issue')
        data = f.readline()
        f.close()

        split = data.split(' ')
        if split[0] == 'Ubuntu' and split[1] == '5.10':
            return True
        else:
            return False

    def haveGCC(version):

        if os.path.exists("/usr/bin/gcc-" + version) and \
           os.path.exists("/usr/bin/g++-" + version):
            return True
        else:
            return False

    
##    if onUbuntu():
##        if haveGCC('4.0'):
##            print "gcc 4.0.2 along with boost 1.33.0, on at least ubuntu"
##            print "5.10, has problems with a statically constructed pointer when"
##            print "dynamically loaded using the multi-threaded boost libraries, "
##            print "which are the default."
##            print "Attempting to use gcc 3.4 ...",
##        if haveGCC('3.4'):
##            print "Found 3.4"
##            env['CC'] = '/usr/bin/gcc-3.4'
##            env['CXX'] = '/usr/bin/g++-3.4'
##        else:
##            print "Need version 3.4 of gcc and g++ to continue."
##            sys.exit()

    SetOption('num_jobs', 2)
    
    env.Append(CPPFLAGS = ['-ftemplate-depth-255', # jbw hack
                           '-DBOOST_PYTHON_SOURCE',
			   '-fpermissive',
                           '-fno-inline'])

    env.Replace(SHLINKFLAGS = ['-fPIC',
                               '-shared'])
    
if env['DEBUG']:
    print "Building DEBUG version"
    env.Append(CPPFLAGS = (platform == 'win32') and ['/Zi', '-D_DEBUG'] or ['-g', '-D_DEBUG'])
elif env['OPT']:
    print "Building O3 OPTIMIZED version"
    env.Append(CPPFLAGS = (platform == 'win32') and ['/O3'] or ['-O3', '-fast', '-mcpu=7450'])
    env.Append(CPPDEFINES = ['NDEBUG'])
else:
    print "Building OPTIMIZED version"
    env.Append(CPPFLAGS = (platform == 'win32') and ['/O2'] or ['-O2'])
    env.Append(CPPDEFINES = ['NDEBUG'])

LibDependency = {
'Producer'    : [OPENGL, OPENTHREADS, 'Producer'],
'osg'         : [OPENGL, OPENTHREADS, 'osg'],
'osgDB'       : [OPENGL, OPENTHREADS, 'osg', 'osgDB'],
'osgFX'       : [OPENGL, OPENTHREADS, 'osg', 'osgDB', 'osgFX', 'osgUtil'],
'osgGA'       : [OPENGL, OPENTHREADS, 'osg', 'osgUtil', 'osgGA'],
'osgParticle' : [OPENGL, OPENTHREADS, 'osg', 'osgDB', 'osgUtil', 'osgParticle'],
'osgProducer' : [OPENGL, OPENTHREADS, 'osg', 'osgDB', 'Producer', 'osgProducer', 'osgUtil', 'osgText', 'osgGA'],
'osgSim'      : [OPENGL, OPENTHREADS, 'osg', 'osgDB', 'osgText', 'osgUtil', 'osgSim'],
'osgTerrain'  : [OPENGL, OPENTHREADS, 'osg', 'osgTerrain', 'osgDB', 'osgFX', 'osgUtil', 'osgText', 'osgGA', 'osgParticle', 'osgSim', 'Producer', 'osgProducer'],
'osgText'     : [OPENGL, OPENTHREADS, 'osg', 'osgDB', 'osgText'],
'osgUtil'     : [OPENGL, OPENTHREADS, 'osg', 'osgUtil'],
'osgScript'   : [OPENGL, OPENTHREADS, 'osg'],
'osgdb_osgScript'      : [OPENGL, OPENTHREADS, 'osg', 'osgGA', 'osgUtil', 'osgDB'],
}

def get_cpp_files(filedir):
    obj_list = []
    # Consider each file in the extension directory:
    for file in os.listdir(filedir):
        if file.endswith('.cpp'):
            # If it is a .cpp file, add it to the list of
            # SharedObject's to build.
            cppfile = os.path.join(libname, file)
            obj_list.append(env.SharedObject(cppfile))
    return obj_list

def build_library(libname, prefix, suffix, install_dir = './', is_dylib = False):
    obj_list = get_cpp_files(libname)

    env['SHLIBPREFIX'] = prefix
    env['SHLIBSUFFIX'] = suffix

    target = os.path.join(install_dir, libname)

    if platform == 'darwin':
        frameworks = ['-framework', 'Python', '-framework', 'OpenGL']
        if env['FRAMEWORK']:
            for f in LibDependency[libname]:
                if f:
                    frameworks.append('-framework')
                    frameworks.append(f)
            if is_dylib:
                LINKFLAGS = ['-Wl,-x',
                             '-Wl,-Sn',
                             '-Wl,-X',
                             '-Wl,-S',
                             '-dynamiclib',
                             "-F" + home + "/Library/Frameworks",
                             '-F/System/Library/Frameworks',
                             frameworks]
            else:
                LINKFLAGS = ['-Wl,-x',
                             '-Wl,-Sn',
                             '-Wl,-X',
                             '-Wl,-S',
                             '-bundle',
                             '-Wl,-bind_at_load',
                             "-F" + home + "/Library/Frameworks",
                             '-F/System/Library/Frameworks',
                             frameworks]
            lib = env.SharedLibrary(target, obj_list, LIBS=['boost_python'], SHLINKFLAGS=LINKFLAGS)
        else:
            if is_dylib:
                pass
            else:
                LINKFLAGS = ['-bundle',
                             '-lX11',
                             '-lm',
                             '-lstdc++',
                             '-lobjc',
                             '-F/System/Library/Frameworks',
                             frameworks,
                             '-framework',
                             'Python',
                             '-framework',
                             'OpenGL'] # OS X dependent

            if not env['DEBUG']:
                LINKFLAGS.append('-Wl,-x')
            lib = env.SharedLibrary(target, obj_list, LIBS=['boost_python'] + LibDependency[libname], SHLINKFLAGS=LINKFLAGS)
    else:
        # When building a debug version under Win32, use the
        # debug libraries of OpenThreads, Producer and OpenSceneGraph
        # by appending the 'd' to the filename.
        if env['DEBUG'] and platform=='win32':
            for i in range(1, len(LibDependency[libname])):
                LibDependency[libname][i] = LibDependency[libname][i] + "d"

        lib = env.SharedLibrary(target,
                                obj_list,
                                LIBS=['boost_python'] + LibDependency[libname])

    return lib

def build_plugin(libname):
    prefix = 'lib'
    suffix = { 'win32' : '.pyd'}.get(platform, '.so')
    return build_library(libname, prefix, suffix)

def build_node_kit(libname):
    prefix = 'lib'
    suffix = { 'win32' : '.pyd', 'darwin' : '.dylib' }.get(platform, '.so')
    return build_library(libname, prefix, suffix, is_dylib = True)

def build_extension(libname):
    prefix = ''
    suffix = { 'win32' : '.pyd'}.get(platform, '.so')
    return build_library(libname, prefix, suffix, install_dir = install_dir)


for libname in modules.ext_modules:
    lib = build_extension(libname)

#for libname in modules.node_kits:
#    lib = build_node_kit(libname)
#
#for libname in modules.plugins:
#    lib = build_plugin(libname)

# Local Variables: 
# mode: python
# comment-column: 40
# End: 
