import sys

# enable python to find the module
module_path = Dir('.').srcnode().abspath
sys.path.append(module_path)
from build.perftest import compile_test

import os

Import('env')
my_env = env.Clone()

def cu_build_function(source, target, env):
  compile_test(str(source[0]), str(target[0]))

# define a rule to build a .cu from a .test
cu_builder = Builder(action = cu_build_function,
                     suffix = '.cu',
                     src_suffix = '.test')
my_env.Append(BUILDERS = {'CUFile' : cu_builder})

# define a rule to build a report from an executable
xml_builder = Builder(action = os.path.join('"' + str(my_env.Dir('.')), '$SOURCE" > $TARGET'),
                      suffix = '.xml',
                      src_suffix = my_env['PROGSUFFIX'])
my_env.Append(BUILDERS = {'XMLFile' : xml_builder})

my_env.Append(CPPPATH = [Dir('.').srcnode(), Dir('#/testing')])

cu_list = []
program_list = []
xml_list = []

build_files = [os.path.join('build', f) for f in ['perftest.py', 'test_function_template.cxx']]

# describe dependency graph:
# xml -> program -> .cu -> .test
for test in my_env.Glob('*.test'):
  cu = my_env.CUFile(test)
  my_env.Depends(cu, build_files)
  cu_list.append(cu)

  prog = my_env.Program(cu)
  program_list.append(prog)

  xml = my_env.XMLFile(prog)
  xml_list.append(xml)

# make aliases for groups of targets
run_performance_tests_alias = my_env.Alias("run_performance_tests", xml_list)
performance_tests_alias     = my_env.Alias("performance_tests", program_list)

# when no build target is specified, by default we build the programs
my_env.Default(performance_tests_alias)

# output a help message
my_env.Help("""
Type: 'scons' to build all performance test programs.
Type: 'scons run_performance_tests' to run all performance tests and output reports.
Type: 'scons <test name>' to build a single performance test program of interest.
Type: 'scons <test name>.xml' to run a single performance test of interest and output a report in an XML file.
""")

