Import('*')
import re
import sys, os, glob, fnmatch

if sys.version_info.major == 3:
    import site_tools.prebuild as prebuild_mod
else:
    import prebuild as prebuild_mod

sys.path.append(os.path.join(Dir('#').abspath, "site_scons", "site_tools"))

cwd = Dir(".").abspath
cwd = re.sub(r'output(_sysmcu|)[\\/]+objs[\\/]+', '', Dir(".").abspath)

objects     = []
sources     = []
assemblys   = []
includes    = []

lst = os.listdir(cwd)
for d in lst:
    path = os.path.join(cwd, d)

    if os.path.isfile(os.path.join(path, 'SConscript')):
        objects += SConscript(os.path.join(d, 'SConscript'), exports='env')

    if glob.glob(os.path.join(path, '*.h')):
        includes.append(str(d))

    if glob.glob(os.path.join(path, '*.c')) or glob.glob(os.path.join(path, '*.s')) or glob.glob(os.path.join(path, '*.S')):
        for f in os.listdir(os.path.join(cwd, str(d))):
            src = os.path.join(str(d), str(f))
            if f.endswith('.c'):
                sources.append(str(src))
            elif f.endswith('.s') or f.endswith('.S'):
                assemblys.append(str(src))

includes = list(set(includes))

if includes:
    for include in includes:
        env.Append(CPPPATH=[Dir(include).abspath])

        include_abspath = Dir(include).abspath
        string = re.sub(r'output(_sysmcu|)[\\/]+objs[\\/]+', '', Dir(".").abspath)

        prebuild_mod.createSymlinkHeader(os.path.join(Dir('#').abspath, env['CEN_HEADER_DIR']), string)

if sources:
    for source in sources:
        m = re.match(r'(.+[/\\])(.+)(\.c$)', source)
        if m:
            target = m.group(2) + ".o"
            objects += env.Object(target, source)

if assemblys:
    for assembly in assemblys:
        m = re.match(r'(.+[/\\])(.+)(\.s$)', assembly)
        if m:
            target = m.group(2) + ".o"
            objects += env.Object(target, assembly)

Return('objects')

