Import('env')

# clone the parent's env so that we do not modify it
my_env = env.Clone()

vars = Variables()

# add a variable to filter source files by a regex
vars.Add('tests', 'Filter test files using a regex', '.')

# update variables
my_env.Help(vars.GenerateHelpText(env))
vars.Update(my_env)

# populate the environment

# with cl we have to do /bigobj
if my_env.subst('$CXX') == 'cl':
  my_env.Append(CPPFLAGS = '/bigobj')

# #include the current directory
my_env.Append(CPPPATH = Dir('.').srcnode())

# find all .cus & .cpps
sources = []
extensions  = ['*.cu', '*.cpp']

# gather sources in the current directorie
for ext in extensions:
  sources.extend(my_env.Glob(ext))

# gather sources from directories
sources.extend(SConscript('backend/SConscript', exports='env'))

# filter sources
import re
filter_exp = 'int main|driver_instance|{0}'.format(my_env['tests'])
pattern = re.compile(filter_exp)
def test_filter(src):
  return pattern.search(src.get_contents())

sources = filter(test_filter, sources)

tester = my_env.Program('tester', sources)

# create a 'unit_tests' alias
unit_tests_alias = my_env.Alias('unit_tests', [tester])

# add the verbose tester to the 'run_unit_tests' alias
run_unit_tests_alias = my_env.Alias('run_unit_tests', [tester], tester[0].abspath + ' --verbose')

# always build the 'run_unit_tests' target whether or not it needs it
my_env.AlwaysBuild(run_unit_tests_alias)

# add the unit tests alias to the 'run_tests' alias
my_env.Alias('run_tests', [tester], tester[0].abspath)

# build children
SConscript('trivial_tests/SConscript', exports='env')

