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


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

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

sys.path.append(os.path.join(Dir('#').abspath, "site_scons", "site_tools"))
cwd = re.sub(r'output(_sysmcu|)[\\/]+objs[\\/]+', '', Dir(".").abspath)

dir_lists = os.listdir(cwd)
for directory in dir_lists:
    path = os.path.join(cwd, directory)

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

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

    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 file in os.listdir(os.path.join(cwd, str(directory))):
            src = os.path.join(str(directory), str(file))
            if file.endswith('.c'):
                sources.append(str(src))
            elif file.endswith('.s') or file.endswith('.S'):
                assemblys.append(str(src))

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

# 添加对当前目录（根目录）的 .c 文件的支持
if glob.glob(os.path.join(cwd, '*.c')):
    for file in os.listdir(cwd):
        if file.endswith('.c'):
            src = file
            match = re.match(r'(.+)(\.c$)', src)
            if match:
                target = match.group(1) + ".o"
                objects += env.Object(target, src)

# 添加对当前目录（根目录）的 .s/.S 文件的支持
if glob.glob(os.path.join(cwd, '*.s')) or glob.glob(os.path.join(cwd, '*.S')):
    for file in os.listdir(cwd):
        if file.endswith('.s') or file.endswith('.S'):
            src = file
            match = re.match(r'(.+)(\.[sS]$)', src)
            if match:
                target = match.group(1) + ".o"
                objects += env.Object(target, 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[\\/]+', '', include_abspath)
        prebuild_mod.createSymlinkHeader(os.path.join(Dir('#').abspath, env['CEN_HEADER_DIR']), string)

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

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

Return('objects')
