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)

# Scan current directory for source files
for item in os.listdir(cwd):
    item_path = os.path.join(cwd, item)
    if os.path.isfile(item_path):
        if item.endswith('.c'):
            sources.append(str(item))
        elif item.endswith('.s') or item.endswith('.S'):
            assemblys.append(str(item))
        elif item.endswith('.h'):
            includes.append(str('.'))
    elif os.path.isdir(item_path) and item != '.' and item != '..':
        directory = item
        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))

includes = list(set(includes))

if includes:
    for include in includes:
        if include == '.':
            # Current directory
            env.Append(CPPPATH=[cwd])
            string = re.sub(r'output(_sysmcu|)[\\/]+objs[\\/]+', '', cwd)
        else:
            # Subdirectory
            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:
        # Handle both current directory files (no path) and subdirectory files (with path)
        match = re.match(r'(.+[/\\])(.+)(\.c$)', source)
        if match:
            # File in subdirectory
            target = match.group(2) + ".o"
            objects += env.Object(target, source)
        else:
            # File in current directory
            match = re.match(r'(.+)(\.c$)', source)
            if match:
                target = match.group(1) + ".o"
                objects += env.Object(target, source)

if assemblys:
    for assembly in assemblys:
        # Handle both current directory files (no path) and subdirectory files (with path)
        match = re.match(r'(.+[/\\])(.+)(\.[sS]$)', assembly)
        if match:
            # File in subdirectory
            target = match.group(2) + ".o"
            objects += env.Object(target, assembly)
        else:
            # File in current directory
            match = re.match(r'(.+)(\.[sS]$)', assembly)
            if match:
                target = match.group(1) + ".o"
                objects += env.Object(target, assembly)

Return('objects')
