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

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
  env = qtee_sdk_env.Clone()
  # Initialize the environment for the target architecture
  env.InitArch('aarch32')

  # 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
#------------------------------------------------------------------------------
if env['PROC'] == 'scorpion':
  env.Append(CCFLAGS = " -mfpu=neon ")

includes = [
  "${BUILD_ROOT}/core/api/services",
  "${BUILD_ROOT}/core/api/kernel/libstd/stringl",
  "${BUILD_ROOT}/ssg/api/securemsm/trustzone/gp",
  "${BUILD_ROOT}/ssg/api/securemsm/trustzone/qsee",
  "${BUILD_ROOT}/ssg/securemsm/secrsa/shared/inc",
  "${BUILD_ROOT}/ssg/securemsm/secmath/shared/inc",
  "${BUILD_ROOT}/ssg/securemsm/trustzone/qsapps/libs/tee_se_utils/inc",
  "${BUILD_ROOT}/ssg/securemsm/trustzone/qsapps/libs/tee_se_api/inc",
  "${SDK_ROOT}/inc/tee_se_utils",
]

if env.StandaloneSdk():
  libs = [
    '$SDK_ROOT/libs/$APP_EXEC_MODE/tee_se_api.lib',
    '$SDK_ROOT/libs/$APP_EXEC_MODE/tee_se_utils.lib'
  ]
else:
  libs = [
    env.SConscript('${BUILD_ROOT}/ssg/securemsm/trustzone/qsapps/libs/tee_se_api/build/SConscript',exports='env'),
    env.SConscript('${BUILD_ROOT}/ssg/securemsm/trustzone/qsapps/libs/tee_se_utils/build/SConscript',exports='env'),
  ]


#----------------------------------------------------------------------------
# App core Objects
#----------------------------------------------------------------------------
sources = [
  'gp_scp11_sample.c',
  'gp_scp11_sample_main.c',
]

app_name = 'scp11smp'

#-------------------------------------------------------------------------------
# Add metadata to image
#-------------------------------------------------------------------------------
md = {
    'appName':       app_name,
    'UUID':          'A6891849-E466-49AB-83A3-E74CCA7D931E',
    'privileges':    [ 'default', 'ESEService', 'SCP11Crypto' ],
    'acceptBufSize': 139264,    # CAPDU(64K) and RAPDU(64K) plus some overhead
    'heapSize':      0x21000,   # At least For accepted CAPDU and RAPDU
}

app_units = env.SecureAppBuilder(
  sources = sources,
  includes = includes,
  metadata = md,
  image = app_name,
  deploy_sources=[sources, 'SConscript'],
  deploy_variants = env.GetDefaultPublicVariants(),
  user_libs = libs
)

#-------------------------------------------------------------------------------
# Must ship the binaries as well as sources above
#-------------------------------------------------------------------------------
env.Deploy(app_units)

op = env.Alias(app_name, app_units)
Return('app_units')

