CMAKE_MINIMUM_REQUIRED(VERSION 3.9)
PROJECT(ipsec C)

IF (SOURCE_PATH)
    SET(CMAKE_SOURCE_DIR ${SOURCE_PATH})
ENDIF ()

INCLUDE(ProcessorCount)
PROCESSORCOUNT(PROCS)

FIND_PROGRAM(NASM nasm)
IF (NOT NASM)
    MESSAGE(FATAL_ERROR "NASM not found")
ENDIF ()

FIND_PROGRAM(MAKE make)
IF (NOT MAKE)
    MESSAGE(FATAL_ERROR "MAKE not found")
ENDIF ()

IF (EXEC_ENV STREQUAL "Windows")
    FIND_PROGRAM(MAKE nmake)
    IF (NOT MAKE)
        MESSAGE(FATAL_ERROR "nmake not found")
    ENDIF ()
ENDIF ()

SET(MAKE_FLAGS)

IF (EXEC_ENV STREQUAL Windows)
    LIST(APPEND MAKE_FLAGS /f win_x64.mak)
ENDIF ()

IF (CMAKE_BUILD_TYPE STREQUAL Debug)
    LIST(APPEND MAKE_FLAGS DEBUG=y)
ENDIF ()

IF (LIBRARY_LINKAGE STREQUAL "static")
    LIST(APPEND MAKE_FLAGS SHARED=n)
ENDIF ()

MESSAGE(STATUS "${MAKE_FLAGS}")
ADD_CUSTOM_TARGET(ipsec-mb ALL
                  COMMAND ${MAKE} -j ${MAKE_FLAGS}
                  WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/
#                  VERBATIM
                  )

SET(LIB_PATH ${CMAKE_SOURCE_DIR}/)
IF (LIBRARY_LINKAGE STREQUAL "dynamic")
    STRING(APPEND LIB_PATH libIPSec_MB.so)
ELSEIF (LIBRARY_LINKAGE STREQUAL "static")
    STRING(APPEND LIB_PATH libIPSec_MB.a)
ELSE ()
    MESSAGE(FATAL_ERROR "Unknown linkage type ${LIBRARY_LINKAGE}")
ENDIF ()
INSTALL(FILES ${LIB_PATH}
        DESTINATION ${CMAKE_SOURCE_DIR}/${CMAKE_BUILD_TYPE}/lib/)
INSTALL(DIRECTORY ${CMAKE_SOURCE_DIR}/include DESTINATION ${CMAKE_SOURCE_DIR}/${CMAKE_BUILD_TYPE}/)