#===========================================================================
#  Copyright (c) 2019 - 2020 Qualcomm Technologies, Inc.
#  All Rights Reserved.
#  Confidential and Proprietary - Qualcomm Technologies, Inc.
#===========================================================================
#
#
# GENERAL DESCRIPTION
#    build script
#                      EDIT HISTORY FOR FILE
#
#  This section contains comments describing changes made to the module.
#  Notice that changes are listed in reverse chronological order.
#
# when       who     what, where, why
# --------   ---     ---------------------------------------------------------
#
#===============================================================================

import os

try:
  Import('env')
except:
  # We're doing an out of tree build so we need to setup the env to build our TA

  exc_obj = Exception('Exiting!...')

  # First, call into the QTEE SDK to get an Environment with all the tools
  try:
    # Either set $QTEE_SDK in the OS environment or pass
    # QTEE_SDK=/path/to/SDK as a SCons commandline argument
    # In this example, the SCons argument takes priority
    sdk_env_name = 'QTEE_SDK'
    sdk_dir = ARGUMENTS.get(sdk_env_name, os.environ.get(sdk_env_name))

    print 'Initialising QTEE SDK..'

    if not sdk_dir:
      print '\nEither set $QTEE_SDK in the OS environment or pass QTEE_SDK=/path/to/SDK as commandline argument..'
      raise exc_obj

    # Call the QTEE SDK SConscript to get a QTEE SDK SCons Environment  
    sdk_sconstruct = os.path.join(sdk_dir,'SConstruct')
    if not os.path.isfile(sdk_sconstruct):
      print '\nQTEE SDK SConstruct($QTEE_SDK/SConstruct) file not found!..'
      raise exc_obj
    qtee_sdk_env = SConscript(sdk_sconstruct)

  except Exception as e:
    if e == exc_obj:
      print exc_obj
    else:
      print '\nUnable to initialize QTEE SDK at ${}: {} '.format(sdk_env_name, sdk_dir)
      # re-raise the exception
      raise
    Exit(1)

  # We've gotten the env, now let's build our TA
  # Initialize the environment for the target architecture
  for arch in ['aarch32', 'aarch64']:
    env = qtee_sdk_env.Clone()

    # Initialize the environment for the target architecture
    env.InitArch(arch)

    # Establish where our compiled artifacts will go
    # out_dir = os.path.join(Dir('.').srcnode().abspath, 'out', env['PROC'])
    # env.Replace(OUT_DIR=out_dir)
    # env.Replace(LIB_OUT_DIR=out_dir)

    # We can call this exact sconscript again, but this time exporting the env we just got
    # so that we aren't tabbing over everthing below this
    this_sconscript = (lambda x:x).func_code.co_filename
    env.SConscript(this_sconscript,exports='env')

  Return()


env = env.Clone()

#------------------------------------------------------------------------------
# We need to specify "neon" to generate SIMD instructions in 32-bit mode
#------------------------------------------------------------------------------


includes = ['${BUILD_ROOT}/apps/securemsm/trustzone/qsapps/loadalgota',
            '${BUILD_ROOT}/apps/securemsm/trustzone/qsapps/tzdrm/tzcommon/common/shared/inc',
            '${BUILD_ROOT}/ssg/securemsm/trustzone/qsapps/libs/secdsplib',
            '${BUILD_ROOT}/ssg/securemsm/trustzone/qsapps/libs/ipprotectorlib',
            '${BUILD_ROOT}/apps/securemsm/trustzone/qsapps/misc_headers',
            '$SDK_ROOT/inc/secdsplib/',
            '$SDK_ROOT/inc/ipprotectorlib',
           ]

#----------------------------------------------------------------------------
# App core Objects
#----------------------------------------------------------------------------
sources = Glob('*.c')
sources_header = Glob('*.h')

if env['PROC'] == 'scorpion':
  app_name = 'loadalgota'
else:
  app_name = 'loadalgota64'

#-------------------------------------------------------------------------------
# Add metadata to image
#-------------------------------------------------------------------------------
md = {
   'appName':    app_name,
   'privileges': ['default', 'DSPSharedChannel', 'ComputeDSPSecureMemAccess', 'AccessControl', 'IPProtector'],
   'heapSize' : 0x400000,
}

libs = []
if env.StandaloneSdk():
  libs.append('$SDK_ROOT/libs/$APP_EXEC_MODE/' + ('dsc_lib64.lib' if env['PROC'] == 'A53_64' else 'dsc_lib.lib'))
  libs.append('$SDK_ROOT/libs/$APP_EXEC_MODE/ipprot_lib.lib')
  #we only need to specify elflib for standalone sdk because the ipprotectorlib sconscript returns both it and elflib
  libs.append('$SDK_ROOT/libs/$APP_EXEC_MODE/elflib.lib')

else:
  libs.append(env.SConscript('${BUILD_ROOT}/ssg/securemsm/trustzone/qsapps/libs/secdsplib/SConscript', exports='env'))
  libs.append(env.SConscript('${BUILD_ROOT}/ssg/securemsm/trustzone/qsapps/libs/ipprotectorlib/SConscript', exports='env'))


deploy_header_files = env.Glob('./*.h')
loadalgota_units = env.SecureAppBuilder(
  sources = sources,
  includes = includes,
  user_libs = libs,
  metadata = md,
  image = app_name,
  deploy_sources = [sources,
                    sources_header,
                    'SConscript'],
  deploy_variants = env.GetDefaultPublicVariants()
)

op = env.Alias(app_name, loadalgota_units)

Return('loadalgota_units')
