from buildutils import *

Import('env', 'install', 'buildSample')
localenv = env.Clone()

if env['HAS_GLIBCXX']:
    stdlib = ['stdc++']
elif env['HAS_LIBCPP']:
    stdlib = ['c++']
else:
    stdlib = []

# (program name, [source files])
samples = [('demo', ['demo.f90'])]

for programName, sources in samples:
    buildSample(localenv.Program, programName, sources,
                F90PATH='#build/src/fortran',
                LIBS=['cantera_fortran']+env['cantera_libs']+stdlib,
                LIBPATH=[env['sundials_libdir'], '#build/lib'])

    # Generate SConstruct files to be installed
    incdirs = [pjoin(localenv['ct_incroot'], 'cantera')] + localenv['extra_inc_dirs']
    libs = ['cantera_fortran'] + localenv['cantera_libs'] + stdlib
    libdirs = ((localenv['ct_libdir'], localenv['sundials_libdir'],
                localenv['blas_lapack_dir']) + tuple(localenv['extra_lib_dirs']))
    linkflags = ('-g', localenv['thread_flags'])

    mak_path = pjoin(localenv['ct_incroot'], 'cantera', 'Cantera.mak')
    if ' ' in mak_path:
        # There is no reasonable way to handle spaces in Makefile 'include'
        # statement, so we fall back to using the relative path instead
        mak_path = os.path.relpath(mak_path, pjoin(localenv['ct_sampledir'], 'f90'))
    localenv['tmpl_Cantera_dot_mak'] = mak_path

    localenv['tmpl_cantera_incdirs'] = repr([x for x in incdirs if x])
    localenv['tmpl_cantera_libs'] = repr(libs)
    localenv['tmpl_cantera_libdirs'] = repr([x for x in libdirs if x])
    localenv['tmpl_cantera_linkflags'] = repr([x for x in linkflags if x])
    localenv['tmpl_cantera_frameworks'] = repr(localenv['FRAMEWORKS'])

    localenv['tmpl_progname'] = programName
    localenv['tmpl_sourcename'] = programName + '.f90'

    sconstruct = localenv.SubstFile('SConstruct', 'SConstruct.in')

    # Generate CMakeLists.txt to be installed
    localenv['cmake_cantera_incdirs'] = ' '.join(quoted(x) for x in incdirs if x)
    localenv['cmake_cantera_libs'] = ' '.join(libs)
    localenv['cmake_cantera_libdirs'] = ' '.join(quoted(x) for x in libdirs if x)
    cmakelists = localenv.SubstFile('CMakeLists.txt', 'CMakeLists.txt.in')

    # Generate Makefile to be installed
    localenv['make_target'] = programName
    localenv['make_sourcefile'] = programName + '.f90'
    makefile = localenv.SubstFile('Makefile', 'Makefile.in')

    install('$inst_sampledir/f90', makefile)
    install('$inst_sampledir/f90', sconstruct)
    install('$inst_sampledir/f90', cmakelists)
