#===============================================================================
#
# mldap  build script
#
# GENERAL DESCRIPTION
#    build script
#
# Copyright (c) 2010 by QUALCOMM, Incorporated.
# All Rights Reserved.
# QUALCOMM Proprietary/GTDR
#
#-------------------------------------------------------------------------------
#
#  $Header: $
#  $DateTime: $
#  $Author: $
#  $Change: $
#                      EDIT HISTORY FOR FILE
#
#  This section contains comments describing changes made to the module.
#  Notice that changes are listed in reverse chronological order.
#
#===============================================================================
import os
Import('env')

env = env.Clone()

#------------------------------------------------------------------------------
# Check if we need to load this script or just bail-out
#------------------------------------------------------------------------------
# alias - First alias is always the target then the other possible aliases
aliases = [
   'mldap'
]

env.InitImageVars(
  alias_list = aliases,       # list of aliases, unique name index [0]
  proc = 'scorpion',          # proc settings
  config = 'apps',            # config settings
  build_tags = ['APPS_PROC', 
     'MLDAP_IMAGE'],  # list of build tags for sub lib scripts
  tools = [
     "${BUILD_ROOT}/core/bsp/build/scripts/scl_builder.py",
     "${BUILD_ROOT}/core/bsp/build/scripts/mbn_builder.py",
     "buildspec_builder.py",
     "${BUILD_ROOT}/tools/build/scons/sectools/sectools_builder.py",
  ],
  
)

if not env.CheckAlias():
   Return()

#------------------------------------------------------------------------------
# Init default values for this PROC/Image
#------------------------------------------------------------------------------

#===============================================================================
# mldap build rules
#===============================================================================

#------------------------------------------------------------------------------
# Configure and load in USES and path variables
#------------------------------------------------------------------------------
env.InitBuildConfig()

#---------------------------------------------------------------------------
# Load in the tools scripts
#---------------------------------------------------------------------------
env.LoadToolScript('arm', toolpath = ['${BUILD_SCRIPTS_ROOT}'])
env.LoadToolScript('apps_defs', toolpath = ['${BUILD_SCRIPTS_ROOT}'])

#------------------------------------------------------------------------------
# Add extension flags for mldap
#------------------------------------------------------------------------------
if env['BUILD_VER'] == "":
   env.Replace(BUILD_VER = '0')

#----------------------------------------------------------------------------
# Enable Stack protection
#----------------------------------------------------------------------------
env.Append(CCFLAGS = " --protect_stack ")

# TODO Not sure why this is needed. mldap must be added somewhere,
# otherwise a CPU without TZ instructions is being used.
# env.Replace(ARM_CPU_SCORPION = '7')
env.Append(CFLAGS = ' --apcs=/ropi/rwpi --lower_ropi --lower_rwpi')
env.Append(ASFLAGS = ' --apcs=/ropi/rwpi ')

env.Append(CPPDEFINES = [
   "MLDAP",
   "BUILD_BOOT_CHAIN",
   "BUILD_BOOT_CHAIN_SPBL",
   "BOOT_LOADER",
   "BOOT_WATCHDOG_DISABLED",
   "FLASH_NAND_SINGLE_THREADED",
   "FLASH_CLIENT_BOOT",
   "FLASH_USE_DM_PAGES",
   "FEATURE_HS_USB_BASIC",
   "BOOT_SBL_H=\\\"boot_comdef.h\\\"",
   "BOOT_CUSTSBL_H=\\\"custsbl.h\\\"",
   "BOOT_MODULE_BUILD_VERSION=" + env['BUILD_VER'],
   "FEATURE_USES_TURBO",
   "RUMIBUILD",
])

#------------------------------------------------------------------------------
# Decide which build steps to perform
#------------------------------------------------------------------------------
# Regular build steps (no filter) is build everything, once a user starts
# using filters we have to make decisions depending on user input.
#
# The LoadAUSoftwareUnits function will take care of filtering subsystem, units, 
# etc.  This is to take care of what steps to enable disable from the top level
# script, such as building files specify in this script i.e. quartz, stubs, etc.

do_local_files = True
do_link = True
do_post_link = True

# Get user input from command line
filter_opt = env.get('FILTER_OPT')

# Limit build processing based on filter option
if filter_opt is not None:
   do_link = False
   do_post_link = False

   if not env.FilterMatch(os.getcwd()):
      do_local_files = False

#-------------------------------------------------------------------------------
# Libraries Section
#-------------------------------------------------------------------------------
core_libs, core_objs = env.LoadAUSoftwareUnits('core')
mldap_units = [core_objs, core_libs]

if do_local_files:
   #============================================================================
   # mldap Environment
   #============================================================================

   #----------------------------------------------------------------------------
   # Begin building mldap
   #----------------------------------------------------------------------------
   env.Replace(TARGET_NAME = 'mldap')
   env.Replace(MLDAP_ROOT = '${COREBSP_ROOT}/securemsm/trustzone/qsapps/mldap')

   #----------------------------------------------------------------------------
   # Generate Scatter Load File (SCL)
   #----------------------------------------------------------------------------
   target_scl = env.SclBuilder('${SHORT_BUILDPATH}/${TARGET_NAME}',
      '${MLDAP_ROOT}/build/mldap.scl')

   mldap_units.extend(target_scl)

if do_link:
   #----------------------------------------------------------------------------
   # Generate mldap ELF
   #----------------------------------------------------------------------------
   libs_path = env['INSTALL_LIBPATH']

   #mldap_elf = '${SHORT_BUILDPATH}/${TARGET_NAME}.elf'

   mldap_elf = env.Program('${SHORT_BUILDPATH}/${TARGET_NAME}', source=[core_objs], LIBS=[core_libs], LIBPATH=libs_path)

   env.Depends(mldap_elf, target_scl)

   mldap_map = env.subst('${SHORT_BUILDPATH}/${TARGET_NAME}.map')
   mldap_sym = env.subst('${SHORT_BUILDPATH}/${TARGET_NAME}.sym')

   env.Clean(mldap_elf, mldap_map)
   env.Clean(mldap_elf, mldap_sym)

if do_post_link:   
   #----------------------------------------------------------------------------
   # Generate mldap MBN
   #----------------------------------------------------------------------------
   mldap_pbn = env.InstallAs('${SHORT_BUILDPATH}/${TARGET_NAME}.pbn',
      mldap_elf)         

   install_root = env.subst('${MBN_ROOT}')
   image_name = "mldap"
   install_unsigned_root = env.SectoolGetUnsignedInstallPath(install_base_dir = install_root)
   env.Replace(MBN_FILE = os.path.join(install_unsigned_root, image_name)) 
   
   mldap_mbn = env.MbnBuilder('${SHORT_BUILDPATH}/${TARGET_NAME}',
      mldap_pbn, IMAGE_TYPE="mldap", MBN_TYPE="elf",
      IMAGE_ID=4, FLASH_TYPE="sdcc")

   #----------------------------------------------------------------------------
   # Sectools signing
   #----------------------------------------------------------------------------
   mldap_sign = env.Command('../../../../../../build/ms/bin/MAYAANAA/signed_mldap.mbn','../../../../../../build/ms/bin/MAYAANAA/unsigned/mldap.mbn',\
                     "java -jar ${BUILD_ROOT}/../common/build/signclient.jar -model INPUT_MODEL_NAME -runtype qc_secimg30_mldap -input $SOURCE -output $TARGET")

   env.Depends(mldap_sign, mldap_mbn)

   #-------------------------------------------------------------------------
   # Build files for PIL driver
   #-------------------------------------------------------------------------
   env.LoadToolScript('pil_splitter_builder', toolpath = ['${BUILD_ROOT}/core/bsp/build/scripts'])
#  unsigned_pil_dir = env.SectoolGetUnsignedInstallPath(install_base_dir = pil_base_dir)
#  mldap_pil = env.PilSplitterBuilder(os.path.join(unsigned_pil_dir, 'mldap.mdt'), mldap_mbn)
#  mldap_pil = env.PilSplitterBuilder(os.path.join(unsigned_pil_dir, 'mldap.mdt'), mldap_sign)
   mldap_pil = env.PilSplitterBuilder('${BUILD_ROOT}/build/ms/bin/PIL_IMAGES/SPLITBINS_${QC_SHORT_BUILDPATH}/mldap.mdt', mldap_sign)

   env.Depends(mldap_pil, mldap_sign)
   #============================================================================
   # Define units that will be built
   #============================================================================
   mldap_units = env.Alias ('arm11_mldap_units', [
      mldap_elf,
      mldap_mbn,
      mldap_pil,
#     sectools_signed_mbn
   ])

# Add aliases
for alias in aliases:
   env.Alias(alias, mldap_units)
