cmake_minimum_required(VERSION 3.16)
project(archery_netcore CXX)

set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR riscv64)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)

if(NOT DEFINED PY_INCLUDE_DIR)
  message(FATAL_ERROR "PY_INCLUDE_DIR not set")
endif()
if(NOT DEFINED PY_LIB)
  message(FATAL_ERROR "PY_LIB not set")
endif()
if(NOT DEFINED PY_EXT_SUFFIX)
  message(FATAL_ERROR "PY_EXT_SUFFIX not set")
endif()
if(NOT DEFINED MAIXCDK_PATH)
  message(FATAL_ERROR "MAIXCDK_PATH not set (need components/3rd_party/pybind11)")
endif()

add_library(archery_netcore MODULE 
  archery_netcore.cpp
  native_logger.cpp
  utils.cpp
  decrypt_ota_file.cpp
  msg_handler.cpp
  tcp_ssl_password.cpp
)

target_include_directories(archery_netcore PRIVATE
  "${PY_INCLUDE_DIR}"
  "${MAIXCDK_PATH}/components/3rd_party/pybind11/pybind11/include"
  "${MAIXCDK_PATH}/components/3rd_party/openssl/include"
  "${CMAKE_CURRENT_SOURCE_DIR}/third_party"  # 添加 nlohmann/json 路径
)

# 尽量减少 .so 体积并增加逆向成本
target_compile_options(archery_netcore PRIVATE
  -Os
  -ffunction-sections
  -fdata-sections
  -fvisibility=hidden
  -fvisibility-inlines-hidden
)
target_link_options(archery_netcore PRIVATE
  -Wl,--gc-sections
  -Wl,-s
)

set_target_properties(archery_netcore PROPERTIES
  PREFIX ""
  SUFFIX "${PY_EXT_SUFFIX}"
)

# OpenSSL (for AES-256-GCM decrypt)
# 使用 MaixCDK 提供的 OpenSSL 库（在 so/maixcam 目录下）
set(OPENSSL_LIB_DIR "${MAIXCDK_PATH}/components/3rd_party/openssl/so/maixcam")
if(EXISTS "${OPENSSL_LIB_DIR}/libcrypto.so")
    target_link_directories(archery_netcore PRIVATE "${OPENSSL_LIB_DIR}")
    target_link_libraries(archery_netcore PRIVATE "${PY_LIB}" crypto ssl)
    message(STATUS "Using OpenSSL from MaixCDK: ${OPENSSL_LIB_DIR}")
else()
    # Fallback: 尝试 find_package 或系统库
    find_package(OpenSSL QUIET)
    if(OpenSSL_FOUND)
        target_link_libraries(archery_netcore PRIVATE "${PY_LIB}" OpenSSL::Crypto OpenSSL::SSL)
    else()
        message(WARNING "OpenSSL not found in MaixCDK, trying system libraries (may fail)")
        target_link_libraries(archery_netcore PRIVATE "${PY_LIB}" crypto ssl)
    endif()
endif()