#===========================================================================
#  Copyright (c) 2011-2019 QUALCOMM Technologies Incorporated.
#  All Rights Reserved.
#  Qualcomm Confidential and Proprietary
#===============================================================================

#-------------------------------------------------------------------------------
# Source PATH
#-------------------------------------------------------------------------------
import os

try:
  #normal builds and integrated apps + sdk builds
  Import('env')
except:
  #standalone TA build against an sdk
  #this sconscript is included in $SDK_ROOT/samples/sampleapp/src
  env = SConscript('../../../external/SConstruct')
  env.InitArch(ARGUMENTS.get('ARCH','aarch64'))
  pass

# Cloning the passed SCons construction environment since changing the 
# environment may interfere with subsequent TA compilations.
env = env.Clone()

# Adding entry for current TA in external build sanity script which tests
# compilation of TAs in external build.
try:
  # Fetch the path of current Sconscript file.
  this_sconscript = (lambda x:x).__code__.co_filename
  env.ExtSdkBldSanity(this_sconscript)
except:
  pass

# The query_supported_cmnlib_api and query_supported_krnl_svc APIs can be used
# to check for the presence of required kernel services and exposed commlonlib
# apis. The compilation of a TA can be decided based on the presence of these
# services or commonlib apis. These are some example use cases of these APIs.

if env.QuerySupportedCmnlibApi("qsee_sfs_open"):
  print("qsee_sfs_open commonlib API is exposed.")

# Set this flag to true if tha current TA is chipset independent and doesn't 
# require to be rebuilt for every chipset.
env['CHIPSET_INDEPENDENT'] = True 

env.Append( CPPFLAGS = ' -Wno-format' )
#env.Append( CPPFLAGS = ' -v' )
aliases = ['tigerfp', 'uefitzt', 'deploy','allapps']

# and 'x86-32' and 'x86-64' for offtarget compilations.
#if env['PROC'] == 'scorpion' or env['PROC'] == 'x86-32':
#  app_name = 'tigerfp'
#else:
#  app_name = 'tigerfp64'

# Specifying the app_name to the construction environment so that build artifacts
# are created with the same name as the provided app_name.
app_name = 'tigerfp'
env['APP_NAME'] = app_name

# The build artifacts should be compiled in chipset specific directories if the TA is
# chipset dependent otherwise its suggested to compile them in common directories so
# that they are not recompiled for each chipset recompilation.
if env.get('CHIPSET_INDEPENDENT'):
  env['OUT_DIR'] = os.path.join(env['BUILD_ROOT'], 'apps/bsp/trustzone/qsapps/${APP_NAME}/build/') 

#env.Replace(OUT_DIR = '${BUILD_ROOT}/ssg/bsp/trustzone/qsapps/tigerfp/build/$PROC')
#env.Replace(LIB_OUT_DIR = '${BUILD_ROOT}/ssg/bsp/trustzone/qsapps/tigerfp/build/${SHORT_BUILDPATH}/$PROC')

includes = [
    '../../../../../../../trustzone_images/core/api/services/',
    '../../../../../../../trustzone_images/ssg/api/securemsm/trustzone/gp',
    '../../../../../../../trustzone_images/ssg/securemsm/trustzone/qsee/include/',
    '../../../../../../../trustzone_images/ssg/securemsm/trustzone/qsapps/common/idl',
    '../../../../../../../trustzone_images/ssg/securemsm/trustzone/qsapps/libs/applib/qsee/src',
    '../../../../../../../trustzone_images/ssg/securemsm/trustzone/qsapps/libs/biometric/inc',
    '../../../../../../sdk/latest/external/inc/biometric/',
#    '../../../../../../../trustzone_images/ssg/securemsm/trustzone/qsapps/tigerfp/include',
#    '../../../../../../../trustzone_images/ssg/securemsm/trustzone/qsapps/tigerfp/src',
#    '../../../../../../../trustzone_images/ssg/securemsm/trustzone/qsapps/tigerfp/src/tzWrappers',
    '../include/',
    '../src/',
    '../src/tzWrappers/',
    '../../../../../../../trustzone_images/ssg/securemsm/trustzone/qsee/mink/include',
    '../../../../../../../trustzone_images/core/api/kernel/libstd/stringl',
]

#----------------------------------------------------------------------------
# App core Objects
#----------------------------------------------------------------------------
from tigerfp import tigerfpSource

print ('+++++++++++++++[compiling files]+++++++++++++++++++++++++++++++')
for fn in tigerfpSource:
  print ("++++       " + fn)
print ('++++++++++++++++++++[total:%d]+++++++++++++++++++++++++++++++++' % len(tigerfpSource))

sources = tigerfpSource

#########################USER DEFINED MACROS[START]################
import os                                                           

os.environ['CHIPSET_NAME'] = "sm8450"
os.environ['COMMIT_SHA1'] = "f160a2bd3e79b720267ea592336e57ea7ac6d9d2"

if os.environ['TARGET_BUILD_VARIANT'] == "eng":
    os.environ['BUILD_MODE'] = "__DEBUG__"
else:
    os.environ['BUILD_MODE'] = "__RELEASE__"
                                                                    
if 'TIGERFP_TEST' in os.environ:                                    
    env.Append(CPPDEFINES = ['__TIGERFP_TEST_MODE'])                
    env.Append(CPPDEFINES = ['__DEBUG'])                            
                                                                    
if 'BUILD_MODE' in os.environ :                                     
    if os.environ['BUILD_MODE'] == "__RELEASE__":                   
        env.Append(CPPDEFINES = ['TIGERFP_RELEASE'])                
        env.Append(CPPDEFINES = ['TIGER_RELEASE'])                  
        env.Append(CPPDEFINES = ['TA_RELEASE'])                     
    else:                                                           
        print ("++++++++ tigerfp debug mode ++++++++++")
# develop TA debug for storage                                      
#env.Append(CPPDEFINES = ['DEV_TA_STORAGE_DEBUG'])                  
# develop TA debug for ATTK/DRK                                     
#env.Append(CPPDEFINES = ['DEV_TA_DRK_DEBUG'])                      
# develop TA debug for dump Request #============SCONS_PATCH: DONOT EDIT======== Respone                       
#env.Append(CPPDEFINES = ['DEV_TA_DUMP_INOUT'])                     
## add env variables                                                
env.Replace(USERNAME = os.environ['USER'])                          
                                                                    
if 'CHIPSET_NAME' in os.environ:                                    
    env.Replace(CHIPSET_NAME = os.environ[ 'CHIPSET_NAME' ].lower())
                                                                    
if 'COMMIT_SHA1' in os.environ:                                     
    env.Replace(COMMIT_SHA1 = os.environ[ 'COMMIT_SHA1' ])          
                                                                    
## add CPPDEFINES                                                   
env.Append(CPPDEFINES = [                                           
    "__USER__=\\\"${USERNAME}\\\"",                           
    "__CHIPSET__=\\\"${CHIPSET_NAME}\\\"",                    
    "__COMMIT_SHA1__=\\\"${COMMIT_SHA1}\\\"",                 
])                                                                  
env.Append(CPPDEFINES = ['__QUALCOMM__'])                           
env.Append(CPPDEFINES = os.environ[ 'CHIPSET_NAME' ].upper())       
# env.Append(CPPDEFINES = ['DEV_TA_DRK_DEBUG'])                     
env.Append(CPPDEFINES = ['SVTS_CMD_ID_SUPPORT'])                    
#                                                                   
env.Append(CPPDEFINES = ['__TA_LOG_TAG__=\\\"TIGERFP-TA\\\"'])
env.Append(CPPDEFINES = ['TZ_MODEL_QCOM'])
#########################USER DEFINED MACROS[END]##################

if env.StandaloneSdk():
  libs = [
    '${SDK_ROOT}/libs/${APP_EXEC_MODE}/biometric.lib',
  ]
else:
  libs = [
    env.SConscript('${BUILD_ROOT}/ssg/securemsm/trustzone/qsapps/libs/biometric/build/SConscript', exports='env'),
  ]

if env['PROC'] == 'scorpion':
  libca = env.SubstRealPath('${MUSL32PATH}/lib/libc.a')
else:
  libca = env.SubstRealPath('${MUSLPATH}/lib/libc.a')

libs.append(env.File(libca))

#deploy_sources = []
#deploy_sources.extend(sources)

#-------------------------------------------------------------------------------
# Add metadata to image
# For debugging purposes UUID is "SampleApp" in hex.
#-------------------------------------------------------------------------------
md = {
   'appName':    app_name,
   'privileges': ['default',
                  'I2C',
                  'OEMUnwrapKeys',
                  'TestSandbox',
                  'CertValidate',
                  'SPI',
                  'SPCOM',
                  'TLMM',
                  'SecureDisplay',
                  'DebugPolicySource',
                  'IntMask',
                  'OEMBuf',
                  'TransNSAddr',
                  'NSSystemReg',
                  'HdcpEncryption',
                  'RTICReport',
                  'System',
                  'HWKeyFactory'
                 ],
  'heapSize': 0x30000,
  'storageFilesNoPersist': False,
  'totalStorageFiles': 300,
  'cryptoSelfTest' : True,
#  'stackSize' : 0x40000,
}

# List of files to to be deployed if TA is to be built in external build.
sconsList = ['SConscript', 'SConstruct']

deploy_sources = [sconsList, env.Glob('../include/*'), sources]

tigerfp_units = env.SecureAppBuilder(
  sources = sources,
  includes = includes,
  metadata = md,
  image = app_name,
  user_libs = libs,
  deploy_sources = deploy_sources,
  deploy_variants = env.GetDefaultPublicVariants()
)

# Set the built TA flag in ARGUMENTS array to True in case TA is chipset independent so
# that other chipset based construction environments can directly read the built TA objects
# and not recompile them.
built_flag = env.subst('${APP_NAME}' + '_BUILT')
if env.get('CHIPSET_INDEPENDENT'):
  ARGUMENTS[built_flag] = True

# Aliasing the TA name with the generated binaries so that any call to TA name will return
# the generated binaries.
op = env.Alias(app_name, tigerfp_units)

# Build artifacts must always be returned using string variables as SCons build environment expects
# the return in this format.
Return('tigerfp_units')
