########## BEGIN SCONSTRUCT ##########

import os, sys, re, yaml
import scons_common
from scons_common import ncpus

YAML_MCD = 'MacroDefinition'
YAML_BDP = 'BuildPath'
YAML_SRC = 'SourcePath'
YAML_ASM = 'AsmPath'
YAML_HED = 'HeadPath'
YAML_SET = 'SettingFile'
YAML_LIN = 'LinkFIle'
YAML_BSW = 'McalCdd'

# Base config set
#-------------------------------------------------------------------------------------------------------
build_mode = ARGUMENTS.get('build_mode', 'unknown')
yaml_file_path = ARGUMENTS.get('yaml_file_path', 'unknown')
compiler = ARGUMENTS.get('compiler', 'unknown')
if compiler == 'GHS_PATH':
    compiler_path_name = 'ghs'
elif compiler == 'HIGHTEC_PATH':
    compiler_path_name = 'hightec'
else:
    compiler_path_name = ''
with open(yaml_file_path, 'r') as file:
    config = yaml.safe_load(file)
#-------------------------------------------------------------------------------------------------------

# setting & link
#-------------------------------------------------------------------------------------------------------
if YAML_SET not in config or YAML_LIN not in config:
    print("[Error]: No setting file and link file.")
    sys.exit(1)

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

settings_file = '.'
for setting_path in config[YAML_SET].split('/'):
    if setting_path == '__COMPILER__':
        settings_file = os.path.join(settings_file, compiler_path_name)
    else:
        settings_file = os.path.join(settings_file, setting_path)
if not os.path.exists(settings_file):
    print("[Error]: Could not find file: ", settings_file)
    sys.exit(1)
else:
    print("======Build Setting File Path======")
    print("|-", settings_file)

links_path = '.'
for link_path in config[YAML_LIN].split('/'):
    if link_path == '__COMPILER__':
        links_path = os.path.join(links_path, compiler_path_name)
    else:
        links_path = os.path.join(links_path, link_path)
if not os.path.exists(links_path):
    print("[Error]: Could not find file: ", links_path)
    sys.exit(1)
else:
    print("======Build Link File Path======")
    print("|-", links_path)

SetOption('num_jobs', ncpus())
#-------------------------------------------------------------------------------------------------------

# Add variables to environment along with some help text
#-------------------------------------------------------------------------------------------------------
vars = Variables(settings_file)
vars.Add('OUTPUT_DIR',          'Path to Build all target files.', 'output')
vars.Add('LOG_DIR',             'Path to store all log files.', 'log')
vars.Add('CPU_TARGET',          'CPU to Build for.  Must match what the compiler is expecting as \'cpu\' option.')
vars.Add('CPU_ARCHI',           'CPU to Build for.  Must match what the compiler is expecting as \'cpu\' option.')
vars.Add('COMPILER_TOOL',       'Custom SCons tool to be used for Building.  Must match the file name located in the site_tools directory.')
vars.Add('COMPILER_ROOT',       'Path to compiler executables.')
vars.Add('COMPILER_FLAGS',      'Compiler flags to use for Building.')
vars.Add('COMPILER_DEFINES',    'Compiler defines to use for Building.')
vars.Add('ASSEMBLER_FLAGS',     'Assembler flags to use for Building.')
vars.Add('ASSEMBLER_DEFINES',   'Assembler defines to use for Building.')
vars.Add('LINKER_FLAGS',        'Linker flags to be used for Building.')
vars.Add('LINKER_FILE',         'Path to linker file to be used during linking.')
vars.Add('ADD_LIBRARIES',       'Names of additional libraries to be included during linking.  These do not need the file extension.')
vars.Add('LIBRARY_PATHS',       'Paths to look for the additional libraries.')
vars.Add('BUILD_TYPE',          'Type of Build to be done.  Options are: DEBUG, PROD, DEVEL')
vars.Add('PROJ_NAME',           'Name of the project to be built.')
vars.Add('OBJECT_FILE',         'path to object files to be added during linking.')
vars.Add('CEN_HEADER_DIR',      'path to centralized header file of project.')
vars.Add('LIBRARY_SEARCH_PATH', 'Path to search a specific library')
vars.Add('CPU_USED', 	        'CPU Used.')
vars.Add('ASW_BUILD_EN',        'Asw .c .cpp build enable')
#-------------------------------------------------------------------------------------------------------

# Initialize the default SCons environment
env = Environment(
    ENV=os.environ,
    variables = vars
)

env['LINKER_FILE'] = links_path

# Generate variables help text
env.Help(vars.GenerateHelpText(env))

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

# Setup logging of output
scons_common.setuplogging(env)

# Validate the mandatory values of the environment
scons_common.validate_environment(env)


# Build target/project name
if env['BUILD_TYPE'] == 'PROD':
	env['PROJ_PREFIX'] = 'P'
elif env['BUILD_TYPE'] == 'DEVEL':
	env['PROJ_PREFIX'] = 'R'
else:
	env['PROJ_PREFIX'] = 'D'
	env['PROJ_SUFFIX'] = 'DEBUG'

# Just keep the name according to project - version is already identified by tag name
env['TARGET_NAME'] = env.subst('$PROJ_NAME') + '_' + env.subst('$PROJ_SUFFIX')

############ START SCONSCRIPT ############
#clone the evironment and setup compiler specific enivronment
env = env.Clone(tools=[env['COMPILER_TOOL']])
env = env.Clone(tools=[env['COMPILER_TOOL'], 'memory_usage'])

#remove all psuedo header file
prebuild_mod.cleanHeaderDir(env['CEN_HEADER_DIR'])


#-------------------------------------------------------------------------------------------------------
objects = []
build_paths = []
source_paths = []
asm_paths = []
header_paths = []
macro_defs = []
#-------------------------------------------------------------------------------------------------------


# Yaml path deal
#-------------------------------------------------------------------------------------------------------
def get_suitable_path(original_path):
    output_path = []
    for path in original_path:
        recent_path = ''
        for dir_name in path.split('/'):
            if dir_name == '__COMPILER__':
                recent_path = os.path.join(recent_path, compiler_path_name)
            elif dir_name != '':
                recent_path = os.path.join(recent_path, dir_name)
        output_path.append(recent_path)
    return output_path

def push_yaml_path_config(data):
    if YAML_BDP in data and isinstance(data[YAML_BDP], list):
        build_paths.extend(get_suitable_path(data[YAML_BDP]))

    if YAML_SRC in data and isinstance(data[YAML_SRC], list):
        source_paths.extend(get_suitable_path(data[YAML_SRC]))

    if YAML_ASM in data and isinstance(data[YAML_ASM], list):
        asm_paths.extend(get_suitable_path(data[YAML_ASM]))

    if YAML_HED in data and isinstance(data[YAML_HED], list):
        header_paths.extend(get_suitable_path(data[YAML_HED]))

def find_banned_path(pass_path, deal_paths):
     pattern = re.compile(r'^S\d{2}E\d{2}_.+')
     for deal_path in deal_paths:
        for dir_name in deal_path.split(os.sep):
            if dir_name == '':
                continue
            if pattern.match(dir_name) and dir_name != pass_path:
                print("[Error]: Prohibited paths: " + dir_name)
                print("[Error]: You can only use " + pass_path + " in this build.")
                sys.exit(1)

push_yaml_path_config(config)

if build_mode == 'qualitytest':
    for build_path in build_paths:
        if build_path.split(os.sep)[0] == 'McalCdd':
            print("[Error]: Prohibited Character [McalCdd] In Qualitytest BuildPath.")
            print("[Error]: You Shoule Use Yaml Files For McalCdd.")
            sys.exit(1)
    if YAML_BSW in config and isinstance(config[YAML_BSW], list):
        for mcalcdd_yaml_name in config[YAML_BSW]:
            mcalcdd_yaml_path = os.path.join('qualitytest', 'source', 'mcalcdd_config', mcalcdd_yaml_name)
            if not os.path.exists(mcalcdd_yaml_path):
                print("[Error]: Can not find " + mcalcdd_yaml_path)
                sys.exit(1)
            with open(mcalcdd_yaml_path, 'r') as mcalcdd_yaml_file:
                mcalcdd_config = yaml.safe_load(mcalcdd_yaml_file)
                push_yaml_path_config(mcalcdd_config)

    qualitytest_section = ARGUMENTS.get('qualitytest_section', 'unknown')
    if qualitytest_section == 'unknown':
        print("[Error]: No qualitytest section name.")
        sys.exit(1)
    find_banned_path(qualitytest_section, build_paths)
    find_banned_path(qualitytest_section, source_paths)
    find_banned_path(qualitytest_section, asm_paths)
    find_banned_path(qualitytest_section, header_paths)
#-------------------------------------------------------------------------------------------------------


# Storage of all objects to be linked
#-------------------------------------------------------------------------------------------------------
if build_paths:
    build_paths = list(dict.fromkeys(build_paths))
    print("======All Build Directories======")
    for build_path in build_paths:
        print("|-", build_path)
        objects += (SConscript(os.path.join(build_path, 'SConscript'),
                    exports = 'env',
                    variant_dir = os.path.join(env.subst('$OUTPUT_DIR'), 'objs', build_path),
                    duplicate=0))
    print("")
#-------------------------------------------------------------------------------------------------------


# Storage of special source files to be linked
#-------------------------------------------------------------------------------------------------------
if source_paths:
    source_paths = list(dict.fromkeys(source_paths))
    print("======Extend Build source files======")
    for build_path in source_paths:
        print("|-", build_path)
        recent_path = ''
        for build_dir in build_path.split('/'):
            if build_dir != '':
                recent_path = os.path.join(recent_path, build_dir)
        source = re.match(r'(.+[/\\])(.+)(\.(c|cpp)$)', recent_path)
        if source:
            target = os.path.join(env.subst('$OUTPUT_DIR'), 'objs',
                                  source.group(1), source.group(2) + ".o")
            objects += env.Object(target, recent_path)
    print("")
#-------------------------------------------------------------------------------------------------------


# Storage of special asm files to be linked
#-------------------------------------------------------------------------------------------------------
if asm_paths:
    asm_paths = list(dict.fromkeys(asm_paths))
    print("======Extend Build asm files======")
    for build_path in asm_paths:
        print("|-", build_path)
        recent_path = ''
        for build_dir in build_path.split('/'):
            if build_dir != '':
                recent_path = os.path.join(recent_path, build_dir)
        asm_file = re.match(r'(.+[/\\])(.+)(\.(s|S)$)', recent_path)
        if asm_file:
            target = os.path.join(env.subst('$OUTPUT_DIR'), 'objs',
                                  asm_file.group(1), asm_file.group(2) + ".o")
            objects += env.Object(target, recent_path)
    print("")
#-------------------------------------------------------------------------------------------------------


# Storage of special head files dir to be linked
#-------------------------------------------------------------------------------------------------------
if header_paths:
    header_paths = list(dict.fromkeys(header_paths))
    print("======Extend head files======")
    for head_path in header_paths:
        print("|-", head_path)
        recent_path = ''
        for head_dir in head_path.split('/'):
            if head_dir != '' and '.h' not in head_dir:
                recent_path = os.path.join(recent_path, head_dir)
                env.Append(CPPPATH=[Dir(recent_path).abspath])
    print("")
#-------------------------------------------------------------------------------------------------------


# Compiler configuration
# -------------------------------------------------------------------------------
CommonMacroDefs = ARGUMENTS.get('CommonMacroDefs', '').split('#')
for CommonMacroDef in CommonMacroDefs:
    if CommonMacroDef != '':
        macro_defs.append(CommonMacroDef)
if YAML_MCD in config and isinstance(config[YAML_MCD], list):
    for CommonMacroDef in config[YAML_MCD]:
        macro_defs.append(CommonMacroDef)
if macro_defs:
    macro_defs = list(dict.fromkeys(macro_defs))
    print("======Definition Of Macros Used======")
    for MacroDef in macro_defs:
        env.Append(CPPDEFINES=MacroDef)
        print("|-", MacroDef)
    print("")
# -------------------------------------------------------------------------------


# Setup output path for debug, hex and A2L files
dbg_path    = os.path.join(env.subst('$OUTPUT_DIR'), 'dbg')
scons_common.create_work_dir(dbg_path)

# Setup link path for build
out_file    = os.path.join(scons_common.create_work_dir(dbg_path), env.subst('$TARGET_NAME'))
rsp_file    = out_file + ".rsp"
T_rsp_path  = scons_common.gen_link_objects_file(rsp_file, objects)
env.Append(LINKCOM=' @'+ T_rsp_path)

# Build final debug, elf
dbg_exe     = env.Program(out_file, objects)

# Setup explicit dependency of elf file to linker script
env.Depends(dbg_exe, env['LINKER_FILE'])

# Setup explicit dependency of elf file to static library file of OS
env.Depends(dbg_exe, env['LIBRARY_PATHS'])


########## END SCONSTRUCT ##########
