import os, subprocess
from config import Package, packages, cc
Import('env')

#
# Need to make a copy because SCons uses the environment
# at it's final state, so StGermain ends up depending on
# StgDomain, etc. 
#

env = env.Clone()
env['CURR_PROJECT'] = 'gLucifer'

#
# Inside each project we will be accessing headers without the
# project name as a prefix, so we need to let SCons know how to
# find those headers.
#

env.Append(CPPPATH=env['build_dir'] + '/include/gLucifer')

#
# Need to include the gLucifer library for binaries.
#

libs = ['gLucifer'] + env.get('LIBS', [])

#
# Keep a list of all the objects we build so we can make a library
# afterwards.
#

#
# Process each directory uniformly.
#

objs = []
suites = []
tst_exp = []
tst_input = []

dirs = Split('Base DrawingObjects libgLucifer')
for d in dirs:

    # Need the module name, which is just the directory.
    mod_name = env['ESCAPE']('"' + ''.join(d.split('/')) + '"')
    version_name = 'GLUCIFER_VERSION'
    cpp_defs = [('CURR_MODULE_NAME', mod_name)] + env.get('CPPDEFINES', [])

    # Setup where to look for files.
    src_dir = d + '/src'
    inc_dir = 'include/gLucifer/' + d

    # Install the headers
    hdrs = env.Install(os.path.join(env['build_dir'],inc_dir), Glob(src_dir + '/*.h'))

    # Build our source files.
    srcs = Glob(src_dir + '/*.c') + Glob(src_dir + '/*.cpp')
    for src in srcs:
        stg_cpp_defs = cpp_defs + [('SOURCE_FILE', '"\\"' + src.name + '\\""')]
        objs += env.SharedObject(src, CPPDEFINES=stg_cpp_defs)

# Need to install headers from libgLucifer.
env.Install(os.path.join(env['build_dir'],'include/gLucifer'), Glob('libgLucifer/src/*.h'))

#
# Build plugins.
#

dirs = [('libgLucifer/Toolbox')]
pl_objs = []
pl_regs = []
for d in dirs:

    if isinstance(d, tuple):
        name = d[1] + 'module'
        d = d[0]
    else:
        name = 'gLucifer_' + d.split('/')[-1] + 'module'

    mod_name = env['ESCAPE']('"' + ''.join(d.split('/')) + '"')
    cpp_defs = [('CURR_MODULE_NAME', mod_name)] + env.get('CPPDEFINES', []) 

    env.Install(os.path.join(env['build_dir'],'include/gLucifer/',d.split('/')[-1]), Glob(d + '/*.h'))

    srcs = Glob(d + '/*.c')
    cur_objs = env.SharedObject(srcs, CPPDEFINES=cpp_defs)

    # If we have shared libraries, build the dynamic plugin.
    if env['shared_libs']:
        lib_pre = env['LIBPREFIXES']
        if not isinstance(lib_pre, list):
            lib_pre = [lib_pre]
        env.SharedLibrary('lib/' + name, cur_objs,
                          SHLIBPREFIX='',
                          LIBPREFIXES=lib_pre + [''],
                          LIBS=libs)

    # If we are building static libs we need to construct a C file
    # mapping the plugin's name to its register function.
    if env['static_libs']:
        pl_regs += [name]

    # Keep track of all the plugin objects.
    pl_objs += cur_objs

#
# Build shared library.
#

if env['shared_libs']:
    env.SharedLibrary('lib/gLucifer', objs)
