cmake_minimum_required(VERSION 3.13)
project(lib-console)

add_subdirectory("lib/argtable3")

file(GLOB CONSOLE_SOURCES "src/*.c")

# Console config options

# Line buffer length
set(CONSOLE_LINE_BUF_LEN "255" CACHE STRING "Line buffer length (max command size)")

# Max number of CLI args
set(CONSOLE_MAX_NUM_ARGS "64" CACHE STRING "Max number of arguments for a command")

# Prompt buffer length
set(CONSOLE_PROMPT_MAX_LEN "32" CACHE STRING "Max prompt string length")

# CLI history length
set(CONSOLE_HISTORY_LEN "32" CACHE STRING "Console history length")

option(CONSOLE_FILE_SUPPORT "Support filesystem operations (history save/load)" ON)

option(CONSOLE_USE_FILE_IO_STREAMS "Use FILE* based console I/O" ON)
option(CONSOLE_USE_TERMIOS "Use unistd/termios to set nonblocking mode & implement bytes available check" ON)
option(CONSOLE_USE_MEMSTREAM "Allow using open_memstream() to generate command hints and report argtable errors" ON)

if(CONSOLE_USE_TERMIOS AND NOT CONSOLE_USE_FILE_IO_STREAMS)
    message( FATAL_ERROR "Can't use TERMIOS without FILE_IO_STREAMS" )
endif()

option(CONSOLE_USE_FREERTOS "Use FreeRTOS" ON)
option(CONSOLE_USE_PTHREADS "Use pthreads" OFF)

# Default timeout for CSP commands
set(CONSOLE_CSP_DEF_TIMEOUT_MS "3000" CACHE STRING "Default timeout for CSP commands (milliseconds)")

option(CONSOLE_TESTING_ALLOC_FUNCS "Test the internal console_malloc etc. functions on startup (with asserts)" OFF)

configure_file(
        "include/console/config.h.in"
        "include/console/config.h"
)

add_library(console ${CONSOLE_SOURCES})

# Enable extra warnings
#set_target_properties(console PROPERTIES COMPILE_FLAGS "-Wall -Wextra" )

target_include_directories(console
        PUBLIC "include" "${CMAKE_CURRENT_BINARY_DIR}/include" # this is where the generated config header is placed
        PRIVATE "src"
)

# Link libraries
set(LIBRARIES argtable3)

if(ESP_PLATFORM)
    set(CONSOLE_USE_FREERTOS ON)
    set(CONSOLE_USE_PTHREADS OFF)
    # special hack for ESP-IDF is needed to allow implementing extern prototypes in main
    set(LIBRARIES ${LIBRARIES} idf::main)
endif()

if(NOT CONSOLE_USE_FREERTOS AND NOT CONSOLE_USE_PTHREADS)
    message( FATAL_ERROR "Required either FreeRTOS or PTHREADS!" )
endif()

if(CONSOLE_USE_PTHREADS)
    set(LIBRARIES ${LIBRARIES} pthread)
endif()

target_link_libraries(console ${LIBRARIES})