from buildutils import *

Import('env', 'build', 'install', 'libraryTargets')

def defaultSetup(env, subdir, extensions):
    return mglob(env, subdir, *extensions)

def baseSetup(env, subdir, extensions):
    escaped_datadir = '\\"' + env['ct_datadir'].replace('\\', '\\\\') + '\\"'
    env.Append(CPPDEFINES={'CANTERA_DATA': escaped_datadir})
    return defaultSetup(env, subdir, extensions)

# (subdir, (file extensions), (extra setup(env)))
libs = [('base', ['cpp'], baseSetup),
        ('thermo', ['cpp'], defaultSetup),
        ('tpx', ['cpp'], defaultSetup),
        ('equil', ['cpp','c'], defaultSetup),
        ('numerics', ['cpp'], defaultSetup),
        ('kinetics', ['cpp'], defaultSetup),
        ('transport', ['cpp'], defaultSetup),
        ('oneD', ['cpp'], defaultSetup),
        ('zeroD', ['cpp'], defaultSetup),
        ('clib', ['cpp'], defaultSetup),
        ]

for subdir, extensions, setup in libs:
    localenv = env.Clone()
    localenv.Prepend(CPPPATH=[Dir('#include'), Dir('#include/cantera/ext')])
    localenv.Append(CCFLAGS=env['warning_flags'])
    source = setup(localenv, subdir, extensions)
    objects = localenv.SharedObject(source)
    localenv.Depends(objects, localenv['config_h_target'])
    libraryTargets.extend(objects)


# build the Cantera static library
localenv = env.Clone()
lib = build(localenv.StaticLibrary('../lib/cantera', libraryTargets,
                                   SPAWN=getSpawn(localenv)))
localenv.Depends(lib, localenv['config_h_target'])
install('$inst_libdir', lib)
env['cantera_staticlib'] = lib

if (localenv['system_sundials'] == 'y'):
    localenv.Append(LIBS=localenv['sundials_libs'],
                    LIBPATH=localenv['sundials_libdir'])
if localenv['blas_lapack_libs']:
    localenv.Append(LIBS=localenv['blas_lapack_libs'],
                    LIBPATH=localenv['blas_lapack_dir'])
if localenv['system_fmt']:
    localenv.Append(LIBS='fmt')

# Build the Cantera shared library
if localenv['layout'] != 'debian':
    if localenv['renamed_shared_libraries']:
        sharedName = '../lib/cantera_shared'
    else:
        sharedName = '../lib/cantera'

    if StrictVersion(SCons.__version__) >= StrictVersion('2.4.0'):
        # InstallVersionedLib only fully functional in SCons >= 2.4.0
        lib = build(localenv.SharedLibrary(sharedName, libraryTargets,
                                           SPAWN=getSpawn(localenv),
                                           SHLIBVERSION=localenv['cantera_pure_version']))
        install(localenv.InstallVersionedLib, '$inst_libdir', lib)
    else:
        lib = build(localenv.SharedLibrary(sharedName, libraryTargets,
                                           SPAWN=getSpawn(localenv)))
        install('$inst_libdir', lib)
    env['cantera_shlib'] = lib
    localenv.Depends(lib, localenv['config_h_target'])
