#===========================================================================
#  Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
#  All Rights Reserved.
#  Confidential and Proprietary - Qualcomm Technologies, Inc.
#===============================================================================

#-------------------------------------------------------------------------------
# Source PATH
#-------------------------------------------------------------------------------
import os

Import('env')
#determine EL0 usermode aarch support
if env['TZ_EXEC_MODE'] == 'aarch32':
  env['EL0_ARCH_SET'] = ['aarch32']
  print("sampleapp/src/SConscript, only aarch32 supported")
else:  #add in config file data for EL0 usermode arch support to allow override of default of both
  chipset= env['CHIPSET']
  cfg_file = '${BUILD_ROOT}/trustzone_images/ssg/bsp/trustzone/qsapps/deploy_sdk/build/sdk_config_' + chipset + '.cfg'
  cfg_files = [(cfg_file,False)]
  env.AddConfigVars(cfg_files, [('EL0_ARCH_SET', 'EL0 supported architectures', ['aarch32','aarch64'])])

if env.StandaloneSdk():
  #standalone TA build against an sdk
  sdk_dir = env['SDK_ROOT']
  if not sdk_dir:
    print('\nEither set $QTEE_SDK in the OS environment or pass QTEE_SDK=/path/to/SDK as commandline argument..')
    Exit(1)

# Chitwan does not support any TA since it has only TN/MN flavr
if env['MSM_ID'] in ['chitwan']:
  Return()

built_tas = []
env = env.Clone()

# pac-ret/bti support has been provided by default to 64-bit library.
# precompiled libv8(without pac-ret/bti) and libv9(with pac-ret/bti) library
# binaries are present in both internal and external builds. for pac-ret/bti
# features TA scons will pick up precompiled libv9 library for 64-bit target
# based on below if condition checks.
armv9 = ''
riscv64 = ''
if env.IsArmv9AppEnvStat():
  armv9 = 'armv9'
if env.IsRiscVAppEnvStat():
  riscv64 = 'riscv64'
  
if env['MSM_ID'] in ['670']:
  env.Append(CPPDEFINES = "IS_sdm710_TARGET")

for target in ['smplap32','smplap64']:
  aliases = []
  if target == 'smplap32':
    if env['APP_EXEC_MODE'] in ['aarch64', 'x86-64']:
      continue
    if env['APP_EXEC_MODE'] == 'aarch32':
      env.Append(CCFLAGS = ' -DAARCH32=1 ')
    env['APP_NAME'] = 'smplap32'
    aliases = ['sampleapp', 'smplap32', 'uefitzt', 'deploy','allapps', 'offtarget', 'verify_deploy_sdk']
    if not env.StandaloneSdk():
      env.Replace(OUT_DIR = '${BUILD_ROOT}/ssg/bsp/trustzone/qsapps/sampleapp/build/${SHORT_BUILDPATH}/${PROC}')
      env.Replace(LIB_OUT_DIR = '${BUILD_ROOT}/ssg/bsp/trustzone/qsapps/sampleapp/build/${SHORT_BUILDPATH}/${PROC}')
  elif target == 'smplap64':
    if env['APP_EXEC_MODE'] in ['aarch32', 'x86-32']:
      continue
    if env['APP_EXEC_MODE'] == 'aarch64':
      env.Append(CCFLAGS = ' -DAARCH64=1 ')
    env['APP_NAME'] = 'smplap64'
    aliases = ['sampleapp', 'smplap64', 'uefitzt', 'deploy','allapps', 'offtarget', 'verify_deploy_sdk']
    if not env.StandaloneSdk():
      env.Replace(OUT_DIR = '${BUILD_ROOT}/ssg/bsp/trustzone/qsapps/smplap64/build/${SHORT_BUILDPATH}/${PROC}')
      env.Replace(LIB_OUT_DIR = '${BUILD_ROOT}/ssg/bsp/trustzone/qsapps/smplap64/build/${SHORT_BUILDPATH}/${PROC}')

  if not env.CheckAlias(aliases):
    continue

  if not env.UserModeSupportsArchitecture():
     print("sampleapp: not building unsupported architecture: ", env["PROC"])
     continue

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

  env.Append(CCFLAGS = ' -DSAMPLE_APP=1 ')
  env.Append(CCFLAGS = ' -Wno-gnu-folding-constant ')

  if env.StandaloneSdk():

    includes = [
      '../../misc_headers',
      '../inc',
      './idl',
      '../inc/crypto_test_vectors',
      os.path.join(sdk_dir, 'inc/sp_iris'), #sp_iris.h
      os.path.join(sdk_dir, 'inc/biometric'), #biometric_result.h
      os.path.join(sdk_dir, 'inc/crypto'),
    ] 

    test_fuse_inc = '../inc/${CHIPSET}'
    if not os.path.isdir(env.subst(test_fuse_inc)):
      test_fuse_inc = '../inc/stubs'

  else:

    includes = [
      '${BUILD_ROOT}/ssg/securemsm/trustzone/qsapps/libs/sp_iris/inc',
      '${BUILD_ROOT}/core/api/services/',
      '${BUILD_ROOT}/ssg/securemsm/uclib/usr/legacy/secmath/shared/inc',
      '${BUILD_ROOT}/ssg/securemsm/uclib/usr/legacy/secrsa/shared/inc',
      '${BUILD_ROOT}/ssg/securemsm/trustzone/qsapps/common/crypto_test_vectors/',
      '${BUILD_ROOT}/ssg/securemsm/trustzone/qsapps/libs/biometric/inc',
      '${BUILD_ROOT}/ssg/securemsm/trustzone/qsapps/sampleapp/inc',
      '${BUILD_ROOT}/ssg/securemsm/trustzone/qsapps/smplserv/idl',
      '${BUILD_ROOT}/ssg/securemsm/trustzone/qsapps/sampleapp/src/idl',
      '${BUILD_ROOT}/ssg/securemsm/trustzone/qsee/mink/include',
    ]

    test_fuse_inc = '${BUILD_ROOT}/ssg/securemsm/trustzone/qsapps/sampleapp/inc/${CHIPSET}'
    if not os.path.isdir(env.subst(test_fuse_inc)):
      test_fuse_inc = '${BUILD_ROOT}/ssg/securemsm/trustzone/qsapps/sampleapp/inc/stubs'

  includes.append(test_fuse_inc)

  offtarget_includes = [
    '${BUILD_ROOT}/ssg/securemsm/sdk/QTEEEmu/misc_bad_includes',
  ]

  if env.OfftargetTesting():
    includes.extend(offtarget_includes)

  #----------------------------------------------------------------------------
  # App core Objects
  #----------------------------------------------------------------------------

  sources = [
          'app_main.c',
          'app_smci_test.c',
          'app_smplserv_test.c',
          'app_sandbox_test.c',
          'app_smplcert_test.c',
          'app_crypto.c',
          'app_sfs.c',
          'app_rsa.c',
          'qsee_api_tests.c',
          'app_cmnlib.c',
          'app_message_passing.c',
          'app_fuses.c',
          'app_stor.c',
          'app_iris.c',
          'app_spcom_test.c',
          'app_bio_lib.c',
          'app_bulletin_board.c',
          'app_hdcp.c',
          'idl/CAppLegacyTest.c',
          'app_gp_fts.c',
          'app_fips_test.c',
          'app_timer.c',
          'app_heap_debugging_test.c',
          'app_hw_key_factory.c',
          'app_listener_buff_test.c',
          'app_ppid.c',
          'app_certification_test.c',
  ]
  
  if env['CHIPSET'] in ['waipio', 'kailua', 'lahaina']:
    sources+=['app_kvstore.c']
  else:
    sources+=['app_kvstoreStub.c']
	
  if env.StandaloneSdk():
    libs = [
      os.path.join('${SDK_ROOT}', 'libs', armv9, '${APP_EXEC_MODE}', 'biometric.lib'),
      os.path.join('${SDK_ROOT}', 'libs', armv9, '${APP_EXEC_MODE}', 'sp_iris.lib'),
    ]
  else:
    libs = [
      env.SConscript('${BUILD_ROOT}/ssg/securemsm/trustzone/qsapps/libs/biometric/build/SConscript', exports = 'env'),
      env.SConscript('${BUILD_ROOT}/ssg/securemsm/trustzone/qsapps/libs/sp_iris/build/SConscript', exports = 'env'),
    ]
  TESTS_TO_STUB = []
  # Kuno does not support RPMB, hence skipping test.
  if env['CHIPSET'] in ['mdm9205', 'kuno', 'pinnacles']:
    TESTS_TO_STUB += [
                       'app_stor.c',
                     ]

  # Expose compiler flag to plug out the stress testing for chipsets.
  if env['MSM_ID'] in ['670', 'kuno']:
    env.Append(CPPDEFINES = "SKIP_STRESS_TEST")

  #kuno has memory shortage and does not support DRM use case, therefore disabling performance and DRM tests
  #also on monaco emmc device there is sail wdog bite due to performance tests so disbaling tests for monaco 
  if env['MSM_ID'] in ['kuno', 'monaco']:
    env.Append(CPPDEFINES = "SKIP_PERF_AND_DRM_TEST")

  # to skip SM3 and SM4 tests for chipsets with CE ver older than 5.7
  if env['MSM_ID'] in ['waipio']:
    env.Append(CPPDEFINES = "SKIP_SM3_SM4_TESTS")
  #Use Stub file if TESTS not Applicable for target
  for x in TESTS_TO_STUB:
    try:
       sources.remove(x)
       sources.append(x.replace('.c','_stub.c'))
    except ValueError:
       pass

  #-------------------------------------------------------------------------------
  # Add metadata to image
  # For debugging purposes UUID is "SampleApp" in hex.
  #-------------------------------------------------------------------------------
  md = {
     'appName':    target,
     'privileges': ['default',
                    'I2C',
                    'OEMUnwrapKeys',
                    'TestSandbox',
                    'CertValidate',
                    'SPI',
                    'SPCOM',
                    'TLMM',
                    'SecureDisplay',
                    'DebugPolicySource',
                    'IntMask',
                    'OEMBuf',
                    'TransNSAddr',
                    'NSSystemReg',
                    'HdcpEncryption',
                    'RTICReport',
                    'System',
                    'HWKeyFactory',
                    'Certification',
                    'PrivacyPreservingID',
                    'KVStore',
                    'CipherDES',
                   ],
    'heapSize': 0x1947AE,
    'stackSize': 0xA000,
    'storageFilesNoPersist': True,
    'totalStorageFiles': 2000,
    'cryptoSelfTest' : True,
    'addrSel' : 'any',
  }
  if env['PROC'] == 'scorpion':
    md['memoryType'] = 'Unprotected'
  if env['PROC'] == 'A53_64':
    md['storageFilesNoPersist'] = False

  # totalStorageFiles is needed for SFS max file limit test.For Kuno, this need not be tested
  # with  2000 files. So, lesser heap requirement and no need for totalStorageFiles flag.
  if env['CHIPSET'] in ['kuno']:
    del md['heapSize']
    del md['totalStorageFiles']

  if env['CHIPSET'] in ['kodiak']:
    # Do not ship for Kodiak
    deploy_variants_list = ['DO_NOT_SHIP']
  else:
    deploy_variants_list = env.GetDefaultPublicVariants()

  sampleapp_units = env.SecureAppBuilder(
    sources = sources,
    includes = includes,
    metadata = md,
    image = target,
    user_libs = libs,
    deploy_variants = deploy_variants_list,
  )

  env.Alias(aliases, sampleapp_units)
  built_tas.append(sampleapp_units)

Return('built_tas')
