cmake_minimum_required(VERSION 3.22)
project(qdigidoccommon VERSION 1.0.0)
if(NOT COMMAND SET_ENV)
	macro(set_env)
		set(${ARGN})
	endmacro()
endif()
set_env( CONFIG_URL "https://id.eesti.ee/config.json" CACHE STRING "Set Config URL" )
set(CMAKE_CXX_STANDARD 23)
find_package(OpenSSL 3.0.0 REQUIRED)
find_package(Qt6 6.2.0 REQUIRED COMPONENTS Widgets Network)

add_library(qdigidoccommon STATIC ${SOURCES} Common.cpp)
target_include_directories(qdigidoccommon PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
target_compile_definitions(qdigidoccommon PUBLIC QT_WARN_DEPRECATED_UP_TO=060200)
target_link_libraries(qdigidoccommon PUBLIC Qt6::Network Qt6::Widgets OpenSSL::SSL)

if(WIN32)
	target_compile_definitions(qdigidoccommon PUBLIC UNICODE WIN32_LEAN_AND_MEAN)
	target_link_libraries(qdigidoccommon PRIVATE Version SetupApi)
elseif(APPLE)
	target_link_libraries(qdigidoccommon PRIVATE "-framework PCSC")
else()
	find_package(PkgConfig REQUIRED)
	pkg_check_modules(PCSCLITE REQUIRED libpcsclite IMPORTED_TARGET)
	target_link_libraries(qdigidoccommon PUBLIC PkgConfig::PCSCLITE)
endif()

if(NOT APPLE)
	target_sources(qdigidoccommon PRIVATE qtsingleapplication/src/qtlocalpeer.cpp qtsingleapplication/src/qtsingleapplication.cpp)
endif()

if( CONFIG_URL )
	set_env( LAST_CHECK_DAYS 4 CACHE STRING "How often check configuration changes" )
	if( LAST_CHECK_DAYS )
		set_source_files_properties(Configuration.cpp PROPERTIES COMPILE_DEFINITIONS LAST_CHECK_DAYS=${LAST_CHECK_DAYS})
	endif()
	if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/config.json AND
		EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/config.ecc AND
		EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/config.ecpub)
		set(CONFIG_DIR ${CMAKE_CURRENT_SOURCE_DIR})
	else()
		file(DOWNLOAD ${CONFIG_URL} ${CMAKE_CURRENT_BINARY_DIR}/config.json)
		string(REPLACE ".json" ".ecc" ECC_URL ${CONFIG_URL})
		file(DOWNLOAD ${ECC_URL} ${CMAKE_CURRENT_BINARY_DIR}/config.ecc)
		string(REPLACE ".json" ".ecpub" PUB_URL ${CONFIG_URL})
		file(DOWNLOAD ${PUB_URL} ${CMAKE_CURRENT_BINARY_DIR}/config.ecpub)
		set(CONFIG_DIR ${CMAKE_CURRENT_BINARY_DIR})
	endif()
	qt_add_resources(qdigidoccommon config BASE ${CONFIG_DIR} PREFIX / FILES
		${CONFIG_DIR}/config.json ${CONFIG_DIR}/config.ecc ${CONFIG_DIR}/config.ecpub
	)
	target_compile_definitions(qdigidoccommon PUBLIC CONFIG_URL="${CONFIG_URL}")
	target_sources(qdigidoccommon PRIVATE Configuration.cpp)
endif()
