cmake_minimum_required(VERSION 3.16)
project(oplabs-mixer-daemon
    VERSION 1.0.0
    DESCRIPTION "OPLabs Mixer Engine Daemon"
    LANGUAGES CXX
)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)

# Find dependencies
find_package(PkgConfig QUIET)

# --- JACK Audio Connection Kit ---
find_library(JACK_LIBRARY jack)
find_path(JACK_INCLUDE_DIR jack/jack.h)

# --- Source files for the daemon (standalone) ---
set(DAEMON_SOURCES
    MixerDaemon.cpp
    MixerIpcServer.cpp
)

# Header-only convenience target for linking to op-pedal sources
# The daemon needs MixerEngine, MixerApi, MixerChannelStrip, MixerBus, etc.
# These are compiled as part of the op-pedal CMake project and linked here.

add_executable(oplabs-mixer-daemon ${DAEMON_SOURCES})

target_include_directories(oplabs-mixer-daemon PRIVATE
    ${CMAKE_CURRENT_SOURCE_DIR}
)

if(JACK_LIBRARY AND JACK_INCLUDE_DIR)
    target_include_directories(oplabs-mixer-daemon PRIVATE ${JACK_INCLUDE_DIR})
    target_link_libraries(oplabs-mixer-daemon PRIVATE ${JACK_LIBRARY})
    message(STATUS "JACK found: ${JACK_LIBRARY}")
    target_compile_definitions(oplabs-mixer-daemon PRIVATE HAS_JACK=1)
else()
    message(WARNING "JACK not found — daemon will be built without audio I/O. "
                    "Install libjack-jackd2-dev or jack-audio-connection-kit.")
endif()

# When built inside the op-pedal CMake tree, link against op-pedal's libraries.
# When built standalone, the user must point CMAKE_PREFIX_PATH to an op-pedal build.
# For standalone development, provide a build wrapper:

if(TARGET op-pedal-lib)
    # We're inside the op-pedal CMake tree
    target_link_libraries(oplabs-mixer-daemon PRIVATE op-pedal-lib)
    message(STATUS "Building inside op-pedal tree — linking op-pedal-lib")
else()
    message(STATUS "Building standalone — user must provide MixerEngine source")
    # In standalone mode, assume the user has checked out the mixer-engine sources
    # and set the MIXER_ENGINE_SOURCE_DIR variable.
    if(MIXER_ENGINE_SOURCE_DIR)
        message(STATUS "Using MixerEngine sources from: ${MIXER_ENGINE_SOURCE_DIR}")
        target_include_directories(oplabs-mixer-daemon PRIVATE
            ${MIXER_ENGINE_SOURCE_DIR}
            ${MIXER_ENGINE_SOURCE_DIR}/../PiPedalCommon
            ${MIXER_ENGINE_SOURCE_DIR}/../modules/SQLiteCpp/include
        )
    endif()
endif()

# Install
install(TARGETS oplabs-mixer-daemon RUNTIME DESTINATION bin)

# Systemd service file
configure_file(
    oplabs-mixer-daemon.service.in
    oplabs-mixer-daemon.service
    @ONLY
)

install(FILES
    ${CMAKE_CURRENT_BINARY_DIR}/oplabs-mixer-daemon.service
    DESTINATION /etc/systemd/system
)
