##############################################################################
#                                                                            #
#                  IMPINJ CONFIDENTIAL AND PROPRIETARY                       #
#                                                                            #
# This source code is the sole property of Impinj, Inc.  Reproduction or     #
# utilization of this source code in whole or in part is forbidden without   #
# the prior written consent of Impinj, Inc.                                  #
#                                                                            #
# (c) Copyright Impinj, Inc. 2009. All rights reserved.                      #
#                                                                            #
##############################################################################


##############################################################################
#
# $Id: SConstruct 66310 2010-12-13 18:37:40Z dshaheen $
# 
#  Description: Root-level build script that defines the build environment
#      and starts the build process
#      
#
##############################################################################


import sys
import SCons.Util
import os
import subprocess

#opts = Options(ARGUMENTS)
opts = Variables()
opts.Add(BoolVariable("debug", "Turn on to enable debugging", 0))
opts.Add(BoolVariable("lib", "Turn on to just build libraries, without qa and unit_test", 0))
opts.Add(BoolVariable("utf", "Turn on to just build libraries and host/unit_test (utf) tree", 0))

# Explicitly stores signatures in ".sconsign.dblite"
# in the top-level SConstruct directory.  This is the default behavior for 
# Scons 0.96.96 and later, but for 0.96.1 (our version) the default behavior
# is  the same as  SConsignFile(None), which writes .sconsign files at each 
# top level directory (including one over in the winddk tree).  This causes 
# problems for multiple users on the same machine, since the .sconsign file
# in the winddk tree can't be overrwritten by another user (unless they have
# admin rights).  So, with the following line, we don't generate files outside
# of the source tree, and multiple users can build on the same machine (albeit
# from their own source tree)
#
SConsignFile()

# Linux builds
if sys.platform.startswith("linux"):
    opts.Add(BoolVariable("mv", "Turn on to do a MontaVista cross-compile", 0))
    opts.Add(BoolVariable("rpi", "Turn on to do a MontaVista cross-compile", 0))
    env = Environment(options = opts, CCFLAGS = "-Wall")
    #print(env.Dump())
    buildos = "linux"
    transportdir = "linux"
    #
    if env["mv"]:
    # If we are doing a build for MontaVista on the IXP465, then we need to
    # change the toolchain.  Also add the default path to the toolchain.
        print("Build for MontaVista on the IXP465 cross-compile.")
        targetplatform = "ixp465"
        env.Replace(CC = "xscale_be-gcc", CXX = "xscale_be-g++",
                    AR = "xscale_be-ar", RANLIB = "xscale_be-ranlib")
        env.PrependENVPath("PATH",
                           "/opt/montavista/pro/devkit/arm/xscale_be/bin")
    elif env["rpi"]:
    # If we are doing a build for RaspberryPi on the ARMv7, then we need to
    # change the toolchain.  Also add the default path to the toolchain.
        print("Build for RaspberryPi on the ARMv7 cross-compile.")
        targetplatform = "armv7l"
        env.Replace(CC = "arm-linux-gnueabihf-gcc", CXX = "arm-linux-gnueabihf-g++",
                    AR = "arm-linux-gnueabihf-ar", RANLIB = "arm-linux-gnueabihf-gcc-ranlib")
    else:
        uname_m = subprocess.check_output(['uname', '-m'])
        uname_m = uname_m.strip('\n')
        targetplatform = uname_m
        print("Build for native host: " + targetplatform)
        #env.Append(CCFLAGS = " -m32")
        env.Append(CCFLAGS = " -fno-stack-protector")

    if env["debug"]:
        print("debug build")
        env.Append(CCFLAGS = " -ggdb")
        env.AppendUnique(CPPDEFINES = { "DEBUG" : 1 })
    else:
        print("release build")
        env.Append(CCFLAGS = " -O3")

    env["LIBS"] = []
    env["LIBPATH"] = [ "." ]
#
else:
    print("Error: Cannot determine build platform!")
    raise SystemExit

# Get the root of the scons directories (i.e., the directory in which this
# script resides)
sconsroot = os.getcwd()

# Set the appropriate debug/non-debug flag
if env["debug"]:
    env.AppendUnique(CPPDEFINES = { "_DEBUG" : 1 })
else:
    env.AppendUnique(CPPDEFINES = { "NDEBUG" : 1 })

# Insert the common include directories into the include paths
env["CPPPATH"] = [sconsroot + "/include",
                  sconsroot + "/include/" + buildos,
                  sconsroot + "/host/include",
                  sconsroot + "/host/include/" + buildos]

installdir = sconsroot + "/bin/" + buildos + "/" + targetplatform + "/"
print("Install folder: " + installdir)
env.Command(installdir, [], 'mkdir -p ' + installdir)

Export("env", "buildos", "transportdir", "installdir")

rfidcommcfg = "RFIDcomm-" + targetplatform + ".cfg"
env["TAR_DEPEND_LIST"] = InstallAs( installdir + "RFIDcomm.cfg", rfidcommcfg )
env["TAR_LIST"] = [ "RFIDcomm.cfg" ]
SConscript([ "host/SConscript" ])

