import os
import sys
import rtconfig
from SCons.Script import *

if os.getenv('RTT_ROOT'):
    RTT_ROOT = os.getenv('RTT_ROOT')
else:
    RTT_ROOT = os.path.normpath(os.getcwd() + '/../../../..')

sys.path = sys.path + [os.path.join(RTT_ROOT, 'tools')]
try:
    from building import *
except:
    print('Cannot find RT-Thread root directory, please check RTT_ROOT')
    print(RTT_ROOT)
    exit(-1)


TARGET = 'rtthread.' + rtconfig.TARGET_EXT

DefaultEnvironment(tools=[])
env = Environment(tools = ['mingw'],
    AS = rtconfig.AS, ASFLAGS = rtconfig.AFLAGS,
    CC = rtconfig.CC, CFLAGS = rtconfig.CFLAGS,
    AR = rtconfig.AR, ARFLAGS = '-rc',
    CXX = rtconfig.CXX, CXXFLAGS = rtconfig.CXXFLAGS,
    LINK = rtconfig.LINK, LINKFLAGS = rtconfig.LFLAGS)
env.PrependENVPath('PATH', rtconfig.EXEC_PATH)

if rtconfig.PLATFORM in ['iccarm']:
    env.Replace(CCCOM = ['$CC $CFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -o $TARGET $SOURCES'])
    env.Replace(ARFLAGS = [''])
    env.Replace(LINKCOM = env["LINKCOM"] + ' --map project.map')

Export('RTT_ROOT')
Export('rtconfig')

SDK_ROOT = os.path.abspath('./')

if os.path.exists(SDK_ROOT + '/libraries'):
    libraries_path_prefix = SDK_ROOT + '/libraries'
else:
    libraries_path_prefix = os.path.dirname(SDK_ROOT) + '/libraries'

SDK_LIB = libraries_path_prefix
Export('SDK_LIB')

def _allow_ch32v20x_d6_in_sdk_package():
    """Official CH32V20x-SDK-for-RTT ships a D8W startup file and Exit()s on D6.
    CH32V203C8T6 is D6. Keep the SDK peripherals and use board/startup_ch32v20x_D6.S.
    Only that package is edited, and only while Exit() is still present, so a
    D8W tree or an already patched file is left untouched.
    """
    import re
    candidates = [
        os.path.join(SDK_ROOT, 'packages', 'CH32V20x-SDK-for-RTT', 'SConscript'),
        os.path.join(libraries_path_prefix, 'ch32v20x_sdk-latest', 'SConscript'),
    ]
    for sc in candidates:
        if not os.path.isfile(sc):
            continue
        with open(sc, 'r', encoding='utf-8') as f:
            text = f.read()
        if 'Exit()' not in text or 'SOC_RISCV_SERIES_CH32V20x_D6' not in text:
            continue
        if not re.search(r'^import os\b', text, re.M):
            text = 'import os\n' + text
        patched, n = re.subn(
            r"if GetDepend\(\['SOC_RISCV_SERIES_CH32V20x_D6'\]\):.*?\n    Exit\(\)\n",
            "if GetDepend(['SOC_RISCV_SERIES_CH32V20x_D6']):\n"
            "    CPPDEFINES.append(\"CH32V20x_D6\")\n",
            text,
            count=1,
            flags=re.S,
        )
        if n == 0 or patched == text:
            continue
        with open(sc, 'w', encoding='utf-8', newline='\n') as f:
            f.write(patched)

_allow_ch32v20x_d6_in_sdk_package()

# prepare building environment
objs = PrepareBuilding(env, RTT_ROOT, has_libcpu=False)

ch32_library = 'ch32v20x_libraries'
rtconfig.BSP_LIBRARY_TYPE = ch32_library

bsp_vdir = 'build'

# common include drivers
objs.extend(SConscript(os.path.join(libraries_path_prefix, 'ch32_drivers','SConscript'), variant_dir='build/libraries/ch32_drivers', duplicate=0))

# make a building
DoBuilding(TARGET, objs)
