#   Copyright (c) 2007 Axel Wachtler
#   All rights reserved.
#
#   Redistribution and use in source and binary forms, with or without
#   modification, are permitted provided that the following conditions
#   are met:
#
#   * Redistributions of source code must retain the above copyright
#     notice, this list of conditions and the following disclaimer.
#   * Redistributions in binary form must reproduce the above copyright
#     notice, this list of conditions and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#   * Neither the name of the authors nor the names of its contributors
#     may be used to endorse or promote products derived from this software
#     without specific prior written permission.
#
#   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
#   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
#   ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
#   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
#   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
#   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
#   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
#   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
#   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
#   POSSIBILITY OF SUCH DAMAGE.

# $Id$

#
# Main Application Sconstruct File
#

#=== modules ==================================================================
import pprint
Import("avr board")
pp = lambda x :  pprint.pprint(x)
ppformat = pprint.pformat

#=== setup build environment ==================================================
avrlocal = avr.Clone()
avrlocal['BOARD_TYPE'] = board
avrlocal['CPU'] = avr['boardopts'][board].cpu
avrlocal['BOOT_LOADER_ADDRESS'] = hex(int(avr['boardopts'][board].blstart/2))
avrlocal['BOOT_LOADER_OFFSET'] = hex(int(avr['boardopts'][board].blstart))

avrlocal['BOARD_MMCU_TABLE'] = dict( [(b, avr['boardopts'][b].cpu) \
                                       for b in avr['boardopts'].keys()])


bdir=Dir(".").path

ccflags = avrlocal.Split("""-Wall -Wundef
             -g$DBGFMT
             -Os
             -pedantic
             -Wall
             -std=c99
             -mmcu=$CPU
             -fshort-enums
             -D$BOARD_TYPE
             %s
              """ % avr['boardopts'][board].get_ccopts())
if ARGUMENTS.get('pedantic', 0):
    ccflags.append("-Werror")

avrlocal['radiolib'] = avrlocal.subst("radio_${BOARD_TYPE}")
avrlocal['iolib'] = avrlocal.subst("io_${BOARD_TYPE}")
avrlocal['CCFLAGS'] = avrlocal.subst(" ".join(ccflags))
avrlocal['LINKFLAGS'] = "-Wl,-Map=${TARGET.dir}/${TARGET.filebase}.map -mmcu=$CPU -L%s" % bdir
avrlocal['AR'] = "avr-ar"
avrlocal['LINK'] = "avr-gcc"
avrlocal['RANLIB'] = "avr-ranlib"

#
avrlocal['CPPPATH'] = ["${dir_install.abspath}/inc","#Src/Lib/Inc","./Inc"]
avrlocal['LIBPATH'] = "${dir_install.abspath}/lib"

# === targets =========================================================
apps = []
myboard = avrlocal['boardopts'][board]

# === generic applications ============================================
applications = {"diag"    : ["diagnostic.c"],
                "rdiag"   : ["diagradio.c"],
                "wuart"   : ["wuart.c"],
                "sniffer" : ["Sniffer/sniffer.c",
                             "Sniffer/sniffer_ctrl.c",
                             "Sniffer/sniffer_scan.c"],
                "wgpio"   : ["wgpio.c"],
                "chsweep" : ["chsweep.c"],
               }

avrlocal_flt = avrlocal.Clone()
avrlocal_flt['LINKFLAGS'] += "-Wl,-u,vfprintf -lprintf_flt"
avrlocal_min = avrlocal.Clone()
avrlocal_min['LINKFLAGS'] += "-Wl,-u,vfprintf -lprintf_min"

float_apps = []

for app, srcs in applications.iteritems():
    if app not in myboard.NO_APP:
        if app in float_apps:
            avrbuild = avrlocal_flt
        else:
            avrbuild = avrlocal_min
        
        # hard replace from code above
        avrbuild['app'] = app
        elf = avrbuild.Program('${app}_${BOARD_TYPE}.elf',
                               srcs,
                               LIBS=["uracoli_${BOARD_TYPE}"])
        hex = avrbuild.Command('${app}_${BOARD_TYPE}.hex',
                               elf,
                               "avr-objcopy -O ihex $SOURCE $TARGET")
        apps += [elf, hex]

appinst = avrlocal.Install('${dir_install.abspath}/bin', apps)


# === Sub project wireless bootloader =========================================
if "wibo" not in avr['boardopts'][board].NO_APP:
    avrwibo = avrlocal.Clone()
    # unelegantly remove the forcing the linkswitch -Wl,-u,vfprintf
    avrwibo['LINKFLAGS'] = avrwibo['LINKFLAGS'].replace("-Wl,-u,vfprintf","")
    avrwibo['LINKFLAGS_BOOT'] = avrwibo['LINKFLAGS'] + \
                                " -Wl,--section-start,.text=$BOOT_LOADER_OFFSET"
    avrwibo['CPPPATH'].append("WiBo/Inc")
    # Wibo bootloader if bootoffset > 0
    if eval(avrwibo['BOOT_LOADER_OFFSET']) != 0:
        wibo_elf = avrwibo.Program("wibo_${BOARD_TYPE}",
                              "WiBo/BootlApp/bootlapp.c",
                               LIBS=["radio_${BOARD_TYPE}"],
                               LINKFLAGS = avrwibo['LINKFLAGS_BOOT'])

        wibo_hex = avrwibo.Command('wibo_${BOARD_TYPE}.hex',
                               wibo_elf,
                               "avr-objcopy -O ihex $SOURCE $TARGET")

        xmpl_elf = avrwibo.Program("xmpl_wibo_${BOARD_TYPE}",
                              "WiBo/XmplApp/main.c",
                               LIBS=["radio_${BOARD_TYPE}", "io_${BOARD_TYPE}"]
                               )

        xmpl_hex = avrwibo.Command('xmpl_wibo_${BOARD_TYPE}.hex',
                               xmpl_elf,
                               "avr-objcopy -O ihex $SOURCE $TARGET")

        appinst += avrwibo.Install('${dir_install.abspath}/bin',
                                   [wibo_elf, wibo_hex,
                                    xmpl_elf, xmpl_hex])

if "wibohost" not in avr['boardopts'][board].NO_APP:
    avrwibohost = avrlocal.Clone()

    avrwibohost['CPPPATH'].append("WiBo/Inc")
    # Wibo Host application
    wibohost_lib = avrwibohost.Library("libwibohost_${BOARD_TYPE}.a",
                              ["WiBo/HostApp/hexparse.c",
                               "WiBo/HostApp/wibohost.c"],
                               CPPDEFINES = ["-DPANID=0xffff", "-DNODEID=0xffff"])

    wibohost_elf = avrwibohost.Program("wibohost_${BOARD_TYPE}",
                          ["WiBo/HostApp/hostapp.c","WiBo/HostApp/cmdif.c"],
                          LIBS=["wibohost_${BOARD_TYPE}",
                                "radio_${BOARD_TYPE}",
                                "io_${BOARD_TYPE}"],
                          CPPDEFINES = ["-DPANID=0xffff", "-DNODEID=0xffff"])

    wibohost_hex = avrwibohost.Command("wibohost_${BOARD_TYPE}.hex", wibohost_elf,
                          "avr-objcopy -O ihex $SOURCE $TARGET")

    appinst += avrwibohost.Install('${dir_install.abspath}/lib', [wibohost_lib])
    appinst += avrwibohost.Install('${dir_install.abspath}/bin', [wibohost_elf, wibohost_hex])



# === Sub project airless bootloader ==========================================
if "albo" not in avr['boardopts'][board].NO_APP:
    avrboot = avrlocal.Clone()
    avrboot['LINKFLAGS_BOOT'] = avrboot['LINKFLAGS'] + \
                                " -Wl,--section-start,.text=$BOOT_LOADER_OFFSET"

    albo_elf = avrboot.Program("albo_${BOARD_TYPE}", "Albo/albo.c")

    albo_hex = avrboot.Command('albo_${BOARD_TYPE}.hex',
                           albo_elf,
                           "avr-objcopy -O ihex $SOURCE $TARGET")
    appinst += avrboot.Install('${dir_install.abspath}/bin', [albo_elf, albo_hex])


# === aliases =========================================================
avrlocal.Alias('a${BOARD_TYPE}', appinst )
