# -*- mode: python; coding: utf-8; -*-

#  Codezero -- a microkernel for embedded systems.
#
#  Copyright © 2009  B Labs Ltd
#
#  This program is free software: you can redistribute it and/or modify it under the terms of the GNU
#  General Public License as published by the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
#  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
#  License for more details.
#
#  You should have received a copy of the GNU General Public License along with this program.  If not, see
#  <http://www.gnu.org/licenses/>.
#
#  Author: Russel Winder

Import('environment', 'previousImage')

taskName = 'test0'

def createTestExecLinkerScript(target, source, env):
    with open(target[0].path, 'w') as outFile:
        with open(source[0].path) as templateFile:
            outFile.write(templateFile.read().replace('__PHYSICAL_BASE_FILE_NAME_MARKER__', source[1].path))

def createTestExecS(target, source, env):
    with open(target[0].path, 'w') as outFile:
        outFile.write('''
.section .testexec

.align 4
.incbin "%s"
.align 4
''' % ( source[0].path ))

try:
    environment['physicalBaseLinkerScript']
except KeyError:
    print '''
####
####  The test0 task cannot be the first task in the list of tasks.
####
'''
    Exit ( 1 )

testTaskEnvironment = environment.Clone()
testTaskEnvironment.Append(CPPPATH=['#' + testTaskEnvironment['posixServicesDirectory'] +'/libposix/include/posix'])
testExecLinkerScript = Command('#build/' + testTaskEnvironment['posixServicesDirectory'] +'/' + taskName + '/test_exec_linker.lds', ['test_exec_linker.lds.in', testTaskEnvironment['physicalBaseLinkerScript']], createTestExecLinkerScript)
testExecEnvironment = testTaskEnvironment.Clone()
testExecEnvironment.Append(LINKFLAGS=['-T' + testExecLinkerScript[0].path])
testExec = testExecEnvironment.Program('test_exec', Glob('src/test_exec/*.[cS]'))
Depends(testExec, testExecLinkerScript)
testExecS = Command('#build/' + testTaskEnvironment['posixServicesDirectory'] + '/' + taskName + '/test_exec.S', testExec, createTestExecS)
program = testTaskEnvironment['buildTask'](taskName, Glob('*.c') + Glob('src/*.[cS]') + testExecS, testTaskEnvironment, previousImage)
Depends(program, testExec)

Return('program')
