# ------------------------------
# cmake config / project
# ------------------------------
cmake_minimum_required(VERSION 4.1.0)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_FLAGS "/EHsc /D_AMD64_ /DWIN32_LEAN_AND_MEAN") # Set C++ exception handler, define platform and ignore some unused headers

project(dbd-unlocker LANGUAGES CXX C)
set_property(GLOBAL PROPERTY USE_FOLDERS ON)

# ------------------------------
# msvc stuff
# ------------------------------
if(CMAKE_GENERATOR MATCHES "Visual Studio")
	string(APPEND CMAKE_CXX_FLAGS " /EHsc /DWIN32_LEAN_AND_MEAN /utf-8 /Zc:char8_t")
	if("${CMAKE_VS_PLATFORM_NAME}" STREQUAL "x64")
		string(APPEND CMAKE_CXX_FLAGS " /D_AMD64_")
	elseif(CMAKE_GENERATOR_PLATFORM STREQUAL "Win32")
		string(APPEND CMAKE_CXX_FLAGS " /D_WIN32_")
	else()
		message(FATAL_ERROR "unhandled architecture")
	endif()
endif()

# ------------------------------------------------------
# folder grouping
# ------------------------------------------------------
function(group_files sources)
	foreach(FILE ${sources})
		get_filename_component(PARENT_DIR "${FILE}" DIRECTORY)
		string(REPLACE "${CMAKE_CURRENT_SOURCE_DIR}/" "" GROUP "${PARENT_DIR}") # remove full dir
		string(REGEX MATCH "[A-Za-z0-9_-]+/[A-Za-z0-9_-]+" GROUPNAME ${GROUP}) # get the first two folders from dir
		string(LENGTH ${GROUPNAME} GROUPLEN) # get project name len
		string(SUBSTRING ${GROUP} ${GROUPLEN} -1 GROUP) # remove project name from dir
		source_group("${GROUP}" FILES "${FILE}") # group file
	endforeach()
endfunction()

# ---------------------
# dependencies
# ---------------------
find_package(OpenSSL REQUIRED)
add_subdirectory(vendor)

# ---------------------
# warnings
# ---------------------
add_library(dbd-unlocker-warnings INTERFACE)
if(CMAKE_GENERATOR MATCHES "Visual Studio")
	target_compile_options(dbd-unlocker-warnings INTERFACE /W4 /WX)
else()
	target_compile_options(dbd-unlocker-warnings INTERFACE -Wall -Wextra -Werror)
endif()

# ------------------------------
# unlocker
# ------------------------------
file(GLOB_RECURSE UNLOCKER_SOURCES CONFIGURE_DEPENDS "src/unlocker/*.cpp" "src/unlocker/*.h")
add_executable(dbd-unlocker ${UNLOCKER_SOURCES})
target_link_libraries(dbd-unlocker PRIVATE dbd-unlocker-warnings ${OPENSSL_LIBRARIES} nerutils wsock32 ws2_32 wininet)
target_include_directories(dbd-unlocker PRIVATE ${OPENSSL_INCLUDE__DIR})

set_property(TARGET dbd-unlocker PROPERTY USE_FOLDERS ON)
set_property(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY VS_STARTUP_PROJECT dbd-unlocker)

group_files("${UNLOCKER_SOURCES}")
