#===========================================================================
#  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()

#------------------------------------------------------------------------------
# We need to specify "neon" to generate SIMD instructions in 32-bit mode
#------------------------------------------------------------------------------
if env['PROC'] == 'scorpion':
    env.Append(CCFLAGS=" -mfpu=neon ")



# Enable QSEE logging
env.Append(CPPDEFINES=["GPQESE_QSEE_LOG_SUPPORTED"])

#-------------------------------------------------------------------------------
# Compiler, object, and linker definitions
#-------------------------------------------------------------------------------
includes = [
    "${BUILD_ROOT}/ssg/securemsm/trustzone/qsapps/libs/biometric/inc",
    "${BUILD_ROOT}/ssg/securemsm/trustzone/qsapps/libs/tee_se_utils/inc",
    "${BUILD_ROOT}/apps/securemsm/trustzone/qsapps/misc_headers",
    "$SDK_ROOT/inc/tee_se_utils",
]

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

if env.StandaloneSdk():
  libs = [
    '$SDK_ROOT/libs/${APP_EXEC_MODE}/tee_se_api.lib',
    '$SDK_ROOT/libs/${APP_EXEC_MODE}/tee_se_utils.lib',
    '$SDK_ROOT/libs/${APP_EXEC_MODE}/biometric.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'),
    env.SConscript('${BUILD_ROOT}/ssg/securemsm/trustzone/qsapps/libs/biometric/build/SConscript',exports='env'),
  ]

#-------------------------------------------------------------------------------
# Add metadata to image
#-------------------------------------------------------------------------------
app_name = 'gpqese'

md = {
    'appName': app_name,
    'description': 'ESE Trusted Application',
    'version': '1.0.0',
    'UUID': '32552B22-89FE-42B4-8A45-A0C4E2DB0326',
    'privileges': ['default', 'ESEService'],
    'acceptBufSize': 0x30000,  # ESE CAPDU(64K) and 2 * RAPDU(64K) plus some overhead
    'heapSize': 0x27000,  # At least For accepted CAPDU and RAPDU
}

app_units = env.SecureAppBuilder(
    sources=sources,
    includes=includes,
    metadata=md,
    image=app_name,
    deploy_sources=[sources, headers, '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')
#===============================================================================
