#=============================================================================
#  Copyright (c) 2020 Qualcomm Technologies, Inc.
#  All Rights Reserved.
#  Confidential and Proprietary - Qualcomm Technologies, Inc.
#=============================================================================
#
#GENERAL DESCRIPTION
#
# This is the TA SConstruct file required for TA compilation which acts as the
# entry point to compile TA shipped to customer. This SConstruct file
# does the following:
# 1. Verifies the command line inputs for sdk version, build root and sdk root.
# 2. Sets up the BUILD_ROOT, SDK_ROOT for SCons construction environment.
# 3. Sets up the construction environment for TA compilation.
# 4. Initialises the environment for TA specific architecture and calls the
#    TA SConscript for TA compilation.
#=============================================================================

import os, traceback
import json

# Getting the file path to the current SConstruct for further processing
this_file_path = (lambda x:x).__code__.co_filename

# Constructing the correct build_root path from current file path.
# Incorrect build_root can hamper relative path traversal for sources
# and libs and cause major errors in subsequent compilation steps.
if '/qtee_tas/' not in this_file_path:
  print('error: Correct the build root folder for current environment.')
  print('       qtee_tas is no more a valid entry point for BUILD_ROOT')
qtee_tas_idx = this_file_path.index('/qtee_tas')
build_root = os.path.join(this_file_path[:qtee_tas_idx], 'qtee_tas')

# Updating the build_root path in the Scons ARGUMENTS array so that it
# is accessible in subsequent TA compilation steps.
ARGUMENTS.update({'BUILD_ROOT': build_root})

# We have different sdk versions pertaining to different chipsets i.e
# 1.1, 1.8, 1.10, 1.10.1 and latest. Extracting passed sdk_version
# from SCons Command Line Arguments.
qtee_sdk_version = ARGUMENTS.get('qtee_sdk_version')
if qtee_sdk_version is None:
  print('error: QTEE SDK version argument not passed. ')
  print('       Pass a valid qtee_sdk_version as: qtee_sdk_version=<version>')
  print('       Valid values for <version> can be: 1.1/1.8/1.10/1.10.1/latest')
  exit(1)

# Constructing the correct sdk_root for the TA so that scripts and tools
# such as ssg_environment, idlcompiler, sdk_tools etc. required for
# TA compilation can be accessed by the TA and correct SCons environment 
# can be set up. 
sdk_root = os.path.join(build_root, 'sdk', str(qtee_sdk_version), 'external')

# Updating the sdk_root path in the Scons ARGUMENTS array so that it
# is accessible in subsequent TA compilation steps.
ARGUMENTS.update({'SDK_ROOT': sdk_root})

# Setting this flag in ARGUMENTS array so that chipset specific scripts
# are loaded at a later point in compilation.
ARGUMENTS['LOAD_CHIPSET_SPECIFIC_TOOLS'] = True

# Check for the presence of entry SConstruct responsible for 
# constructing TA SCons environment. Do this instead of relying on
# scons to print an error if the SDK scons file invocation fails.
# Scons only prints a warning if a scons invocation fails, i.e.:
# 'scons: warning: Ignoring missing SConscript '[path]'
sdk_scons = os.path.abspath(os.path.join(sdk_root,'SConstruct'))
if not os.path.isfile(sdk_scons):
  print('error: QTEE SDK SConstruct file not found [{}]'.format(sdk_scons))
  print('       Pass a valid path as an argument: QTEE_SDK=[path to SDK]')
  Exit(1)

# Try to call the entry SConstruct to create SCons environment for our TA
# Failure in environment construction will raise errors and ulitmately
# stop TA compilation.
try:
  base_env = SConscript(sdk_scons)

except:
  print('error: Exception when processing {}'.format(sdk_scons))
  traceback.print_exc()
  Exit(1)

# Fetching the chipset argument from command line since different chipsets 
# can try to build same TA differently. 
# Fall back to chipsets set in DEFAULT_TARGETS if no chipset argument is 
# passed on command line.
if ARGUMENTS.get('CHIPSET'):
  chipsets = ARGUMENTS.get('CHIPSET').split(',')
else:
  chipsets = base_env['DEFAULT_TARGETS']
  print('Chipset argument not passed ')
  print('Building the target for the following chipsets: ', chipsets)

# Build the TA for applicable architectures. Initialise only with 'aarch64' if
# building a 64bit TA and only with 'aarch32' if building 32bit TA. Both can be
# used if both TA architectures are to be built.
for aarch in ['aarch64']:

  for chipset in chipsets:
    # Don't muck around with the base environment.  Invoking the builder
    # that compiles and signs the TA for one chipset _may_ update the
    # construction environment in a way that would interfere with
    # building for a different chipset.

    env = base_env.Clone()
    env['CHIPSET'] = chipset
    tooldir = os.path.join(env.subst("$SDK_ROOT"), "scripts")
    env.Tool('qcscons_replacement', toolpath = [tooldir])
    env.Tool('sdk_tools', toolpath = [tooldir])

    if not base_env.get('MINKIDL_HAS_RUN'): 
      env.Tool('idlcompiler', toolpath = [tooldir])
      base_env['MINKIDL_HAS_RUN'] = True

    env['CHIPSET'] = chipset
    env.InitArch(aarch) 
    # Call the SConscript to start building the TA with current env.
    env.SConscript('SConscript_v2', exports='env')

Return()
