Import('env', 'gegl_env')

import os

testlib_env = env.Clone()

def is_csource(fn):
    return os.path.isfile(fn) and os.path.splitext(fn)[1] == '.c'

def is_test(fn):
    return fn.startswith('test-')

tests_sources = [fn for fn in os.listdir("./") if is_test(fn) and is_csource(fn)]
testlib_sources = [fn for fn in os.listdir("./") if not is_test(fn) and is_csource(fn)]

testlib_env.Append(LIBS=['mypaint'])
testlib_env.Append(CPPPATH=['../'], LIBPATH=['../..'])

if testlib_env['enable_gperftools']:
    testlib_env.ParseConfig('pkg-config --cflags --libs libprofiler')
    testlib_env.Append(CPPDEFINES='HAVE_GPERFTOOLS')

lib_builder = testlib_env.SharedLibrary if env['use_sharedlib'] else testlib_env.StaticPicLibrary
lib_builder(target='../../mypaint-tests', source=testlib_sources)

tests_env = testlib_env.Clone()

# Build individual tests
tests_env['LIBS'].remove('mypaint') # Workaround: ordering wrong when using Prepend on some systems
tests_env.Prepend(LIBS=['mypaint-tests', 'mypaint'])

# Standard tests
for source in tests_sources:
    target = os.path.splitext(source)[0]
    tests_env.Program(target=target, source=source)

# Gegl tests
gegl_tests_env = gegl_env.Clone()
gegl_tests_sources = [os.path.join('./gegl', fn) for fn in os.listdir("./gegl") if is_test(fn) and is_csource(os.path.join('./gegl', fn))]

if gegl_tests_env['enable_gegl']:
    gegl_tests_env.Append(CPPPATH=['../gegl', '..'])
    gegl_tests_env.Append(LIBPATH=['../..'])
    gegl_tests_env['LIBS'].remove('mypaint') # Workaround: ordering wrong when using Prepend on some systems
    gegl_tests_env.Prepend(LIBS=['mypaint-gegl', 'mypaint-tests', 'mypaint'])
    for source in gegl_tests_sources:
        target = os.path.splitext(source)[0]
        target = os.path.basename(target)
        gegl_tests_env.Program(target=target, source=source)
