# Copyright (c) 2019-2020, 2022 Qualcomm Technologies, Inc.
# All Rights Reserved.
# Confidential and Proprietary - Qualcomm Technologies, Inc.

import os

# First, call into the QTEE SDK to get an Environment with all the tools
try:
  sdk_dir = "../.."

  print("Initialising QTEE SDK..")
  # Call the QTEE SDK SConscript to get a QTEE SDK SCons Environment
  qtee_sdk_env = SConscript(os.path.join(sdk_dir,'SConstruct'))

except:
  print("Unable to initialize QTEE SDK at: {}".format(os.path.realpath(sdk_dir)))

  #re-raise the exception
  raise
  Exit(1)

# This example builds both 32bit and 64 bit versions of the example CA/TA
for arch in ["aarch32", "aarch64"]:
  env = qtee_sdk_env.Clone()

  # Initialize the environment for the target architecture
  # note: for off-target builds aarchXX is mapped to x86-XX
  env.InitArch(arch)

  out_dir = os.path.join(Dir(".").srcnode().abspath, "out", env["SHORT_BUILDPATH"], "${PROC}")
  env.Replace(OUT_DIR=out_dir)
  env.Replace(LIB_OUT_DIR=out_dir)

  # Call the TA and common SConscripts
  ta = env.SConscript("./TA/src/SConscript", exports="env")
  env.SConscript("./common/src/SConscript", exports="env")

  # Build the CA and install the TA if off-target.
  if env.OfftargetTesting():
    # Install the TA, so we can pick up its install location in the CA SConscript.
    env.Replace(TA_INSTALL_PATH= "${BUILD_ROOT}/build/ms/bin/ote/TA/${SHORT_BUILDPATH}/${PROC}/")

    installed_ta = env.Install(env['TA_INSTALL_PATH'], ta)
    env.Alias('installed_ta', installed_ta)

    # Call the CA SConscripts
    env.SConscript("./CA/src/SConscript", exports="env")
    env.SConscript("./test/src/SConscript", exports="env")
