#===========================================================================
#  Copyright (c) 2011-2016, 2017 QUALCOMM Technologies Incorporated.
#  All Rights Reserved.
#  Qualcomm Confidential and Proprietary
#===========================================================================
#
#
# 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
# --------   ---     ---------------------------------------------------------
#
#===============================================================================

#-------------------------------------------------------------------------------
# Source PATH
#-------------------------------------------------------------------------------
import os
Import('env')

env = env.Clone()

project_name = 'mz' 

#------------------------------------------------------------------------------
# MZ SConscripr functions
#------------------------------------------------------------------------------
def MZ_LOGD(str):
    print("[MZ_DBG] " + str)

# get SAFE env variable and print it
def local_get_env(env_variable):
    ret_env_variable = os.getenv(env_variable, 'environment variable not available')
    MZ_LOGD(env_variable + ' : ' + ret_env_variable)
    return ret_env_variable

CHIPSET = env['CHIPSET']
TARGET_BUILD_VARIANT = os.environ['TARGET_BUILD_VARIANT']

# MZ custom config. It can be set as 32 or 64 to use for other configuration below.
TA_TARGET_ARCH = "32"
if CHIPSET in ['waipio']:
    TA_TARGET_ARCH = "64"

MZ_LOGD("CHIPSET : " + CHIPSET)

if os.path.exists(env['BUILD_ROOT'] + '/ssg'):
    QSEE_APP_DIR = env['BUILD_ROOT'] + "/ssg"
else:
    QSEE_APP_DIR = env['BUILD_ROOT'] + "/core"

if not hasattr(env, 'IMAGE_ALIASES'):
    MZ_LOGD("Not Image_aliases")
    aliases = []
    aliases = ['mz',]
    env.Replace(OUT_DIR = QSEE_APP_DIR + "/bsp/trustzone/qsapps/mz/build")
    env.Replace(LIB_OUT_DIR = QSEE_APP_DIR + "/bsp/trustzone/qsapps/mz/build/" + "${SHORT_BUILDPATH}")

env.Append(LINKFLAGS=' -no-threads ')

#------------------------------------------------------------------------------
# MZ Defines
#------------------------------------------------------------------------------
if env['PROC'] == 'scorpion':
    env.Append(CCFLAGS = " -mfpu=neon ")

env.Append(CFLAGS = ' -fstack-protector-all -DSWD -DMZ_QSEE -DTA_BUILD -DENABLE_QSEE_LOGGING -DQSEE ')
env.Append(CCFLAGS = ' -Wno-error -Wno-unused-value -Wno-address-of-packed-member -O0 ')
env.Append(CFLAGS = ' -Dqsee_' + CHIPSET + ' ') # this define is mandatory, inside sources can be found defines like 'qsee_msm8976'

if TARGET_BUILD_VARIANT in ['eng', 'userdebug']:
    MZ_LOGD("MODE : dbg")
    env.Append(CFLAGS = ' -DENABLE_DEBUGGING -D__FILENAME__=__FILE__ -g -DDEBUG ')
else:
    MZ_LOGD("MODE : usr")
    env.Append(CFLAGS = ' -DRELEASE -D__FILENAME__=\"\" ')

#------------------------------------------------------------------------------
# MZ Source PATH
#------------------------------------------------------------------------------
MZ_ROOT_PATH = QSEE_APP_DIR + "/securemsm/trustzone/qsapps/mz/"

#------------------------------------------------------------------------------
# MZ Version and patch
#------------------------------------------------------------------------------
with open(MZ_ROOT_PATH + "version_ta", 'r') as reader:
   lines = reader.readlines()
CONFIG_BASELINE_CL = lines[1].rstrip()
CONFIG_MZ_VERSION = lines[0].rstrip()

CONFIG_MZ_VERSION_MAJOR, CONFIG_MZ_VERSION_MINOR, CONFIG_MZ_VERSION_PATCH = CONFIG_MZ_VERSION.split('.')

env.Append(CFLAGS = ' -DBASELINE_CL=\\"' + CONFIG_BASELINE_CL + '\\"')
env.Append(CFLAGS = ' -DVERSION_NUMBER=\\"' + CONFIG_MZ_VERSION + '\\"')
env.Append(CFLAGS = ' -DVERSION_NUMBER_MAJOR=' + CONFIG_MZ_VERSION_MAJOR)
env.Append(CFLAGS = ' -DVERSION_NUMBER_MINOR=' + CONFIG_MZ_VERSION_MINOR)
env.Append(CFLAGS = ' -DVERSION_NUMBER_PATCH=' + CONFIG_MZ_VERSION_PATCH)

#------------------------------------------------------------------------------
# MZ includes
#------------------------------------------------------------------------------
incl_common = [
    "${INC_ROOT}/core/api/services",
    "${INC_ROOT}/core/kernel/smmu/ACv3.0/common/inc",
    QSEE_APP_DIR +"/api/securemsm/trustzone/qsee",
    QSEE_APP_DIR + "/securemsm/accesscontrol/api",
    MZ_ROOT_PATH + "src",
    MZ_ROOT_PATH + "src/common/include",
    MZ_ROOT_PATH + "src/common/log/inc",
    MZ_ROOT_PATH + "src/common/version", 
    MZ_ROOT_PATH + "include",
    MZ_ROOT_PATH + "src/daemon/inc", 
    MZ_ROOT_PATH + "swd/common",
]

#----------------------------------------------------------------------------
# App core Objects
#----------------------------------------------------------------------------
sour_common = [
    MZ_ROOT_PATH + "swd/qsee/qseeAgentMain.c",
    MZ_ROOT_PATH + "swd/common/tl_handler.c",
    MZ_ROOT_PATH + "swd/common/mz_wb_aes_ctr.c",

    MZ_ROOT_PATH + "src/common/log/src/mz_log.c",
    MZ_ROOT_PATH + "src/common/version/version_info.c",
]

arm_libs = [
    File(env.SubstRealPath('${LLVMLIB}/libclang_rt.builtins-arm.a'))
]
if env["PROC"] == "scorpion":
    arm_libs.append(File(env.SubstRealPath('${MUSL32PATH}/lib/libc.a')))
else:
    arm_libs.append(File(env.SubstRealPath('${MUSLPATH}/lib/libc.a')))

privileges = ['default',
              'System',
              'I2C',
              'OEMUnwrapKeys',
              'CertValidate',
              'SPI',
              'TLMM',
              'SecureDisplay',
             ]

target_name = project_name
app_name = project_name

#-------------------------------------------------------------------------------
# Add metadata to image
#-------------------------------------------------------------------------------
sources = [
    sour_common,
]

md = {
    'appName': app_name,
    'privileges': privileges,
}

if not CHIPSET in ['sdm855', 'sm8250', 'lahaina']:
    if env['PROC'] == 'scorpion':
        md['memoryType'] = 'Unprotected'

md['heapSize'] = 0x13000
mz_units = env.SecureAppBuilder(
    sources = sources,
    includes = incl_common,
    metadata = md,
    image = target_name,
    user_libs = arm_libs,
)

if hasattr(env, 'IMAGE_ALIASES'):
    for image in env['IMAGE_ALIASES']:
        env.Alias(image, mz_units)
else:
    env.Alias(aliases, mz_units)
