# Build script for the silk loader

import sys
import os
from waflib import Logs

def options(opt):
    opt.load('gcc')


def configure(conf):
    # Find our binary tools
    conf.find_program('arm-none-eabi-gcc', var='CC', mandatory=True)
    conf.env.AS = conf.env.CC
    conf.find_program('arm-none-eabi-gcc-ar', var='AR', mandatory=True)

    conf.load('gcc')

    for tool in 'ar objcopy'.split():
        conf.find_program('arm-none-eabi-' + tool, var=tool.upper(), mandatory=True)

    # Set up our compiler configuration
    CPU_FLAGS = ['-mcpu=cortex-m3', '-mthumb']
    OPT_FLAGS = ['-Os', '-g']
    C_FLAGS = [
        '-std=c11', '-ffunction-sections',
        '-Wall', '-Wextra', '-Werror', '-Wpointer-arith',
        '-Wno-unused-parameter', '-Wno-missing-field-initializers',
        '-Wno-error=unused-function', '-Wno-error=unused-variable',
        '-Wno-error=unused-parameter', '-Wno-error=unused-but-set-variable',
        '-Wno-packed-bitfield-compat'
        ]
    LINK_FLAGS = ['-Wl,--gc-sections', '-specs=nano.specs']

    conf.env.append_unique('CFLAGS', CPU_FLAGS + OPT_FLAGS + C_FLAGS)
    conf.env.append_unique('LINKFLAGS', LINK_FLAGS + CPU_FLAGS + OPT_FLAGS)

    conf.env.append_unique('DEFINES', ['_REENT_SMALL=1'])

    # Load up other waftools that we need
    conf.load('objcopy ldscript', tooldir='waftools')

def build(bld):
    elf_node = bld.path.get_bld().make_node('loader.elf')

    linkflags = ['-Wl,-Map,loader.map']

    sources = ['src/**/*.c']

    includes = ['src']

    bld.program(features="objcopy",
                source=bld.path.ant_glob(sources),
                includes=includes,
                target=elf_node,
                ldscript='src/stm32f4_loader.ld',
                linkflags=linkflags,
                objcopy_bfdname='ihex',
                objcopy_target=elf_node.change_ext('.hex'))
    import objcopy
    bld(rule=objcopy.objcopy_simple_bin, source='loader.elf', target='loader.bin')

# vim:filetype=python