cmake_minimum_required(VERSION 3.31)

project(LunarWM LANGUAGES C)

set(CMAKE_C_STANDARD 23)
set(CMAKE_C_STANDARD_REQUIRED 23)
set(CMAKE_CXX_STANDARD 23)

add_compile_options(
	-fstack-protector-strong
	-fwrapv
)
add_compile_definitions(
	WLR_USE_UNSTABLE
	XR_USE_PLATFORM_EGL
	XR_USE_GRAPHICS_API_OPENGL_ES
)

find_package(PkgConfig REQUIRED)

pkg_check_modules(WAYLAND REQUIRED IMPORTED_TARGET GLOBAL wayland-server)
pkg_check_modules(EGL REQUIRED IMPORTED_TARGET egl)
pkg_check_modules(GLES2 REQUIRED IMPORTED_TARGET glesv2)
pkg_check_modules(WLROOTS REQUIRED IMPORTED_TARGET wlroots-0.20)
pkg_check_modules(XKBCOMMON REQUIRED IMPORTED_TARGET xkbcommon)
pkg_check_modules(OPENXR REQUIRED IMPORTED_TARGET openxr)
pkg_check_modules(LUA REQUIRED IMPORTED_TARGET lua)

find_program(WAYLAND_SCANNER_EXECUTABLE wayland-scanner REQUIRED)
message(STATUS "Found wayland-scanner at ${WAYLAND_SCANNER_EXECUTABLE}")
pkg_get_variable(WAYLAND_PROTOCOLS_DIR wayland-protocols pkgdatadir)
message(STATUS "Found wayland-protocols at ${WAYLAND_PROTOCOLS_DIR}")
pkg_get_variable(WAYLAND_SCANNER_PKGDATA_DIR wayland-scanner pkgdatadir)
message(
  STATUS "Found wayland-scanner pkgdatadir at ${WAYLAND_SCANNER_PKGDATA_DIR}")

include(FetchContent)

FetchContent_Declare(
	raylib
	GIT_REPOSITORY https://github.com/slendidev/raylib.git
	GIT_TAG "lunar"
	GIT_SHALLOW 1
)
set(OPENGL_VERSION "ES 3.0")
set(PLATFORM DRM)
set(BUILD_EXAMPLES OFF)
FetchContent_MakeAvailable(raylib)

add_executable(${PROJECT_NAME})
target_sources(${PROJECT_NAME} PUBLIC
	src/vec.c

	src/RayExt.c
	src/Config.c
	src/LunarWM.c
	src/main.c
)
target_link_libraries(${PROJECT_NAME} PUBLIC
	PkgConfig::XKBCOMMON
	PkgConfig::WAYLAND
	PkgConfig::EGL
	PkgConfig::GLES2
	PkgConfig::WLROOTS
	PkgConfig::OPENXR
	PkgConfig::LUA

	raylib
)

# Wayland protocol codegen
set(XDG_SHELL_XML
	${WAYLAND_PROTOCOLS_DIR}/stable/xdg-shell/xdg-shell.xml
)

set(XDG_SHELL_HEADER
	${CMAKE_BINARY_DIR}/xdg-shell-protocol.h
)

set(XDG_SHELL_C
	${CMAKE_BINARY_DIR}/xdg-shell-protocol.c
)

add_custom_command(
	OUTPUT ${XDG_SHELL_HEADER}
	COMMAND ${WAYLAND_SCANNER_EXECUTABLE} server-header
		${XDG_SHELL_XML} ${XDG_SHELL_HEADER}
	DEPENDS ${XDG_SHELL_XML}
	COMMENT "Generating xdg-shell-protocol.h (server header)"
	VERBATIM
)

add_custom_command(
	OUTPUT ${XDG_SHELL_C}
	COMMAND ${WAYLAND_SCANNER_EXECUTABLE} private-code
		${XDG_SHELL_XML} ${XDG_SHELL_C}
	DEPENDS ${XDG_SHELL_XML}
	COMMENT "Generating xdg-shell-protocol.c"
	VERBATIM
)

add_custom_target(xdg_shell_protocol
	DEPENDS ${XDG_SHELL_HEADER} ${XDG_SHELL_C}
)

add_library(xdg_shell STATIC
	${XDG_SHELL_C}
)

add_dependencies(xdg_shell xdg_shell_protocol)

target_include_directories(xdg_shell PUBLIC
	${CMAKE_BINARY_DIR}
)

add_dependencies(${PROJECT_NAME} xdg_shell_protocol)

target_link_libraries(${PROJECT_NAME} PRIVATE xdg_shell)

target_include_directories(${PROJECT_NAME} PRIVATE
	${CMAKE_BINARY_DIR}
)

