cmake_minimum_required(VERSION 3.25)
project(lab LANGUAGES C)

# clangd reads compile_commands.json to learn the flags.
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

# Settings for every user-space target. C23 with language extensions on
# (-std=gnu23); no -Wpedantic, since GNU extensions are normal in low-level
# code. _GNU_SOURCE declares every POSIX and GNU API in the C library headers.
function(lab_options target)
  target_compile_features(${target} PRIVATE c_std_23)
  target_compile_options(${target} PRIVATE
    -Wall -Wextra -Wshadow -Wformat=2 -Wimplicit-fallthrough -Wstrict-prototypes)
  target_compile_definitions(${target} PRIVATE _GNU_SOURCE)
endfunction()

# ---- The library: every .c file in lib/ ------------------------------------
# PUBLIC include directories go to everything that links the library, so the
# program can include klog.h, and klog.h can include the driver's
# uapi/klog_ioctl.h.
file(GLOB lib_sources CONFIGURE_DEPENDS lib/*.c)
add_library(klog STATIC ${lib_sources})
target_include_directories(klog PUBLIC lib driver/uapi)
lab_options(klog)

# ---- The program: every .c file in app/ ------------------------------------
# readline (apt: libreadline-dev) is found with pkg-config. To add another
# library, find its pkg-config name (`pkg-config --list-all`) and repeat the
# pkg_check_modules line for it.
find_package(PkgConfig REQUIRED)
pkg_check_modules(READLINE REQUIRED IMPORTED_TARGET readline)

file(GLOB app_sources CONFIGURE_DEPENDS app/*.c)
add_executable(app ${app_sources})
target_link_libraries(app PRIVATE klog PkgConfig::READLINE)
lab_options(app)

# ---- The driver -------------------------------------------------------------
# The kernel has its own build system (kbuild), so CMake only runs
# `make -C driver`. That needs the kernel tree in kbuild/ (./make_kbuild.sh).
# Each build also refreshes driver/compile_commands.json, the driver's flags
# for clangd.
set(KBUILD_DIR ${CMAKE_SOURCE_DIR}/kbuild)
set(DRIVER_DIR ${CMAKE_SOURCE_DIR}/driver)

if(NOT EXISTS ${KBUILD_DIR}/Makefile)
  message(WARNING
    "There is no kernel tree in kbuild/, so the driver is not built. "
    "Run ./make_kbuild.sh in the project folder, then configure again.")
else()
  add_custom_target(driver ALL
    COMMAND make --no-print-directory -C ${DRIVER_DIR}
    COMMENT "Building the driver"
    USES_TERMINAL)

  # Build the driver once now if it never was, so clangd knows its flags
  # without waiting for the first build.
  if(NOT EXISTS ${DRIVER_DIR}/compile_commands.json)
    message(STATUS "Building the driver once, for driver/compile_commands.json")
    execute_process(
      COMMAND make --no-print-directory -C ${DRIVER_DIR}
      RESULT_VARIABLE driver_result
      OUTPUT_QUIET)
    if(NOT driver_result EQUAL 0)
      message(WARNING "The driver did not build; see the errors above.")
    endif()
  endif()
endif()
