import os
import sys
import rtconfig

RTT_ROOT = os.path.normpath(os.getcwd() + '/../..')
sys.path = sys.path + [os.path.join(RTT_ROOT, 'tools')]
import mdk

target = 'rtthread-mini2440'
projects = []

AddOption('--target',
                  dest='target',
                  type='string',
                  help='set target project: mdk')

if GetOption('target'):
	SetOption('no_exec', 1)

TARGET = target + '.' + rtconfig.TARGET_EXT

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

Export('env')
Export('RTT_ROOT')
Export('rtconfig')
Export('projects')
Export('TARGET')

if env['PLATFORM'] == 'win32' and rtconfig.PLATFORM == 'gcc':
    import win32file
    import win32event
    import win32process
    import win32security

    def my_spawn(sh, escape, cmd, args, spawnenv):
        for var in spawnenv:
            spawnenv[var] = spawnenv[var].encode('ascii', 'replace')

        sAttrs = win32security.SECURITY_ATTRIBUTES()
        StartupInfo = win32process.STARTUPINFO()
        newargs = ' '.join(map(escape, args[1:]))
        cmdline = cmd + " " + newargs

        # check for any special operating system commands
        if cmd == 'del':
            for arg in args[1:]:
                win32file.DeleteFile(arg)
            exit_code = 0
        else:
            # otherwise execute the command.
            hProcess, hThread, dwPid, dwTid = win32process.CreateProcess(None, cmdline, None, None, 1, 0, spawnenv, None, StartupInfo)
            win32event.WaitForSingleObject(hProcess, win32event.INFINITE)
            exit_code = win32process.GetExitCodeProcess(hProcess)
            win32file.CloseHandle(hProcess);
            win32file.CloseHandle(hThread);
        return exit_code

    env['SPAWN'] = my_spawn

objs = SConscript(RTT_ROOT + '/src/SConscript', variant_dir='build/src', duplicate=0)
objs = objs + SConscript(RTT_ROOT + '/libcpu/SConscript', variant_dir='build/libcpu', duplicate=0)

if rtconfig.RT_USING_WEBSERVER:
	objs = objs + SConscript(RTT_ROOT + '/components/net/webserver/SConscript', variant_dir='build/net/webserver', duplicate=0)

if rtconfig.RT_USING_RTGUI:
	objs = objs + SConscript(RTT_ROOT + '/examples/gui/SConscript', variant_dir='build/examples/gui', duplicate=0)

# board build script
objs = objs + SConscript('SConscript', variant_dir='build/bsp', duplicate=0)

# component script 
Repository(RTT_ROOT)
objs = objs + SConscript('components/SConscript')

env.Program(TARGET, objs)
env.AddPostAction(TARGET, rtconfig.POST_ACTION)

if GetOption('target') == 'mdk':
	mdk.MDKProject('project.uV2', projects)
