CMAKE_MINIMUM_REQUIRED(VERSION 3.9)
PROJECT(isal 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 ()

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

SET(MAKE_FLAGS "-f")

IF (EXEC_ENV STREQUAL Windows)
    STRING(APPEND MAKE_FLAGS " Makefile.nmake /E CC=cl AS=nasm")
ELSEIF (EXEC_ENV STREQUAL Linux)
    STRING(APPEND MAKE_FLAGS "Makefile.unx")
ENDIF ()

ADD_CUSTOM_TARGET(isal ALL
                  COMMAND ${MAKE} ${MAKE_FLAGS}
                  WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/
                  )

SET(LIB_PATH ${CMAKE_SOURCE_DIR}/bin/)
IF (LIBRARY_LINKAGE STREQUAL "dynamic")
    STRING(APPEND LIB_PATH isal.so)
ELSEIF (LIBRARY_LINKAGE STREQUAL "static")
    STRING(APPEND LIB_PATH isa-l.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}/)