import os
import multiprocessing

PROGRAM = "testsuite"
LIBS = "../gel"
UNITY = "Unity/src/"
CFLAGS = ["-Wall", "-Wextra", "-g", "-O0",
          "-DGEL_PAGEMANAGER_CONFIGURATION_HEADER=\\\"gel_conf.h\\\""]
MODULES = ["pid", "pagemanager", "collections", "serializer",
           "debounce", "keyboard", "timer", "parameter", "data_structures", "wearleveling",
           "circular_event_log"]
RBGEN = "ruby ./Unity/auto/generate_test_runner.rb"

# Creates a Phony target


def PhonyTargets(
        target,
        depends,
        action,
        env=None,
):
    if not env:
        env = DefaultEnvironment()
    t = env.Alias(target, depends, action)
    env.AlwaysBuild(t)


externalEnvironment = {}
if 'PATH' in os.environ.keys():
    externalEnvironment['PATH'] = os.environ['PATH']

env_options = {
    "ENV": externalEnvironment,
    "CPPPATH": [UNITY, LIBS, ".", "../"],
    "CCFLAGS": CFLAGS,
}

env = Environment(**env_options)

unity = Glob("{}*.c".format(UNITY))
libs = Glob("{}/**/*.c".format(LIBS))

EXE = ""
programs = []

for mod in MODULES:
    tests = Glob("./{}/*.c".format(mod), strings=True)
    for t in [x for x in tests if not str.endswith(x, "_Runner.c")]:
        sources = unity+libs
        env.Command(t.replace(".c", "_Runner.c"), t, "{} {}".format(RBGEN, t))
        sources.append(t)
        sources.append(t.replace(".c", "_Runner.c"))
        name = t.replace(".c", "")
        programs.append(env.Program(name, sources))
        EXE += "./{} && ".format(name)

EXE += "true"

PhonyTargets('test', programs, EXE)
