cmake_minimum_required(VERSION 3.13)
project(uEXAMPLE LANGUAGES C VERSION 0.0.1.0)

enable_language(C)
enable_language(ASM)

set(CMAKE_VERBOSE_MAKEFILE ON)
set(UPQCL_LIBRARY_VER ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH})
set(CMAKE_C_STANDARD 99)

# Global configuration
string(APPEND CMAKE_C_FLAGS "-Os ")
string(APPEND CMAKE_C_FLAGS "-Wno-ignored-qualifiers ")
string(APPEND CMAKE_C_FLAGS "-Wall ")
string(APPEND CMAKE_C_FLAGS "-Werror ")
string(APPEND CMAKE_C_FLAGS "-Wextra ")
string(APPEND CMAKE_C_FLAGS "-Wpedantic ")
string(APPEND CMAKE_C_FLAGS "-Wshadow ")
string(APPEND CMAKE_C_FLAGS "-Wno-variadic-macros ")
string(APPEND CMAKE_C_FLAGS "-Wno-undef ")
string(APPEND CMAKE_C_FLAGS "-Wunused-result ")
string(APPEND CMAKE_C_FLAGS "-Wmissing-prototypes ")
string(APPEND CMAKE_C_FLAGS "-Wvla ")
string(APPEND CMAKE_C_FLAGS "-Wredundant-decls ")
string(APPEND CMAKE_C_FLAGS "-fno-common  ")
string(APPEND CMAKE_C_FLAGS "-DSTM32F4 -DCRYPTO_ITERATIONS=1")

set(uEXAMPLE_SRC
  ${PROJECT_SOURCE_DIR}/src/common/fips202.c
  ${PROJECT_SOURCE_DIR}/src/common/keccakf1600.S
  ${PROJECT_SOURCE_DIR}/src/common/crypto_hashblocks_sha512_inner32.s
  ${PROJECT_SOURCE_DIR}/src/common/crypto_hashblocks_sha512.c
  ${PROJECT_SOURCE_DIR}/src/common/randombytes.c
  ${PROJECT_SOURCE_DIR}/src/common/hal-stm32f4.c
  ${PROJECT_SOURCE_DIR}/src/saber/cbd.c
  ${PROJECT_SOURCE_DIR}/src/saber/kem.c
  ${PROJECT_SOURCE_DIR}/src/saber/mul.S
  ${PROJECT_SOURCE_DIR}/src/saber/NTT_inv_inner.S
  ${PROJECT_SOURCE_DIR}/src/saber/NTT_inv.S
  ${PROJECT_SOURCE_DIR}/src/saber/NTT_pk.S
  ${PROJECT_SOURCE_DIR}/src/saber/NTT.S
  ${PROJECT_SOURCE_DIR}/src/saber/pack_unpack.c
  ${PROJECT_SOURCE_DIR}/src/saber/poly.c
  ${PROJECT_SOURCE_DIR}/src/saber/SABER_indcpa.c
  ${PROJECT_SOURCE_DIR}/src/saber/verify.c)

add_library(
  uexample_obj OBJECT
  ${uEXAMPLE_SRC})
target_include_directories(
  uexample_obj PRIVATE
  ${PROJECT_SOURCE_DIR}/3rd/libopencm3/include
  ${PROJECT_SOURCE_DIR}/src/common
  ${PROJECT_SOURCE_DIR}/src/sabre)

add_executable(
  uexample_test
  ${uEXAMPLE_SRC}
  ${PROJECT_SOURCE_DIR}/src/test.c
)

target_include_directories(
  uexample_test PRIVATE
  ${PROJECT_SOURCE_DIR}/3rd/libopencm3/include
  ${PROJECT_SOURCE_DIR}/src/common
  ${PROJECT_SOURCE_DIR}/src/saber)

target_link_libraries(
    uexample_test PRIVATE
    --static -Wl,--start-group -lc -lgcc -lnosys -Wl,--end-group
    -T${PROJECT_SOURCE_DIR}/src/stm32f405x6.ld
    -nostartfiles -Wl,--gc-sections
    -L${PROJECT_SOURCE_DIR}/3rd/libopencm3/lib -lm -lopencm3_stm32f4
)

add_custom_command(
  TARGET uexample_test POST_BUILD
  COMMAND ${OBJCOPY} -Obinary uexample_test uexample_test.bin
  COMMENT "Invoking: objcopy")

add_custom_target(
  flash
  COMMAND st-flash write uexample_test.bin 0x8000000
  COMMENT "Flashing device")
