#
# Copyright (c) 2022 Nordic Semiconductor ASA
#
# SPDX-License-Identifier: LicenseRef-Nordic-5-Clause
#

cmake_minimum_required(VERSION 3.20.0)

find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})
project(nrf_wifi_sta_xip)

target_include_directories(app PUBLIC ${ZEPHYR_BASE}/subsys/net/ip)

target_sources(app PRIVATE src/main.c)

# zephyr/modules/nrf_wifi/bus/CMakeLists.txt forces both to 0 for the whole build.
zephyr_compile_definitions(NRF53_ERRATA_43_ENABLE_WORKAROUND=1)
zephyr_compile_definitions(NRF53_ERRATA_159_ENABLE_WORKAROUND=1)

if(CONFIG_CODE_DATA_RELOCATION)
  # hostap is built into libzephyr, so relocate by file instead of LIBRARY.
  # utils, drivers, l2_packet and common stay internal: the Zephyr glue and
  # nRF70 driver callbacks call them outside the supplicant thread.
  get_target_property(zephyr_srcs zephyr SOURCES)
  set(hostap_srcs ${zephyr_srcs})
  list(FILTER hostap_srcs INCLUDE REGEX "^${ZEPHYR_HOSTAP_MODULE_DIR}/")
  if(NOT CONFIG_XIPG_HOSTAP_FULL)
    list(FILTER hostap_srcs EXCLUDE REGEX "/src/(utils|drivers|l2_packet|common)/")
  endif()
  list(LENGTH hostap_srcs n)
  message(STATUS "Relocating ${n} hostap files to EXTFLASH")
  zephyr_code_relocate(FILES ${hostap_srcs} LOCATION EXTFLASH_TEXT NOCOPY)
  zephyr_code_relocate(FILES ${hostap_srcs} LOCATION RAM_DATA)

  if(NOT CONFIG_NORDIC_QSPI_NOR_XIP)
    # Gated XIP: QSPI is only active while hostap code can run.
    set(glue ${ZEPHYR_BASE}/modules/hostap/src)
    set(gate ${CMAKE_CURRENT_SOURCE_DIR}/src/gate)
    list(TRANSFORM zephyr_srcs REPLACE "^${glue}/supp_main.c$" "${gate}/supp_main.c")
    set_property(TARGET zephyr PROPERTY SOURCES ${zephyr_srcs})
    set_source_files_properties(${ZEPHYR_HOSTAP_MODULE_DIR}/src/utils/eloop.c
      TARGET_DIRECTORY zephyr PROPERTIES COMPILE_OPTIONS "-include;${gate}/eloop_gate.h")
    set_source_files_properties(${glue}/supp_api.c
      TARGET_DIRECTORY zephyr PROPERTIES COMPILE_OPTIONS "-include;${gate}/mutex_gate.h")
    target_sources(app PRIVATE src/gate/xip_gate.c)

    if(CONFIG_CUSTOM_LINKER_SCRIPT MATCHES "_psa")
      # PSA callers that run outside the supplicant thread.
      set(psa_gate "-include;${gate}/psa_gate.h")
      set(nrf_sec ${ZEPHYR_NRF_MODULE_DIR}/subsys/nrf_security/src/zephyr)
      set_source_files_properties(${nrf_sec}/psa_crypto_init.c ${nrf_sec}/mbedtls_heap.c
        TARGET_DIRECTORY mbedtls_zephyr PROPERTIES COMPILE_OPTIONS "${psa_gate}")
      set_source_files_properties(${ZEPHYR_NRF_MODULE_DIR}/subsys/net/lib/nrf70_fw_ext/ext_fw_load.c
        TARGET_DIRECTORY zephyr PROPERTIES COMPILE_OPTIONS "${psa_gate}")
      if(CONFIG_XIPG_GATE_TCP)
        set_source_files_properties(${ZEPHYR_BASE}/subsys/net/ip/tcp.c
          TARGET_DIRECTORY subsys__net__ip PROPERTIES COMPILE_OPTIONS "${psa_gate}")
      endif()
    endif()
  endif()
endif()
