cmake_minimum_required(VERSION 3.20)
project(PacManager VERSION 1.0.0 LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)

# The repo-root `version` file is the single source of truth for release
# versioning. It is read at configure time and compiled into the binaries, so a
# running app knows which release it was built from.
file(READ ${CMAKE_CURRENT_SOURCE_DIR}/version PACMANAGER_VERSION)
string(STRIP "${PACMANAGER_VERSION}" PACMANAGER_VERSION)

# Reading it above only happens during configuration, and bumping the file is
# not otherwise a reason to configure again: without this, `cmake --build` after
# a version bump kept building the previous version into the binary.
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
    ${CMAKE_CURRENT_SOURCE_DIR}/version)

# Find Qt6
find_package(Qt6 REQUIRED COMPONENTS Widgets Network)

# zlib reads the deflated entries of a .fwspacm package. Qt links it anyway, so
# it is present on any system this builds on; there is no public Qt API for ZIP.
find_package(ZLIB REQUIRED)

# Main executable
set(SOURCES
    src/main.cpp
    src/main-window.cpp
    src/pacman-manager.cpp
    src/plugin-manager.cpp
    src/history-manager.cpp
    src/package-model.cpp
    src/update-manager.cpp
    src/app-logging.cpp
    src/app-settings.cpp
    src/language-manager.cpp
    # Logic layer: background workers, the plugin package installer and the
    # controller the screens delegate to.
    src/workers.cpp
    src/zip-archive.cpp
    src/plugin-package.cpp
    src/app-core.cpp
    # Interface: one file per screen under pages/, on top of the logic layer.
    pages/page.cpp
    pages/ui-kit.cpp
    pages/dashboard-page.cpp
    pages/browse-page.cpp
    pages/cleanup-page.cpp
    pages/history-page.cpp
    src/log-manager.cpp
    pages/logs-page.cpp
    pages/plugins-page.cpp
    pages/settings-page.cpp
    resources/resources.qrc
)

set(HEADERS
    include/package-manager.h
    include/pacman-manager.h
    include/plugin-manager.h
    include/provider-plugin.h
    include/main-window.h
    include/history-manager.h
    include/package-model.h
    include/update-manager.h
    include/app-logging.h
    include/app-settings.h
    include/language-manager.h
    include/workers.h
    include/progress-tracker.h
    include/zip-archive.h
    include/plugin-package.h
    include/app-core.h
    include/log-manager.h
    pages/page.h
    pages/ui-kit.h
    pages/dashboard-page.h
    pages/browse-page.h
    pages/cleanup-page.h
    pages/history-page.h
    pages/logs-page.h
    pages/plugins-page.h
    pages/settings-page.h
)

add_executable(${PROJECT_NAME} ${SOURCES} ${HEADERS})

target_include_directories(${PROJECT_NAME} PRIVATE include pages)
target_link_libraries(${PROJECT_NAME} PRIVATE Qt6::Widgets Qt6::Network ZLIB::ZLIB)
target_compile_definitions(${PROJECT_NAME} PRIVATE
    FWSPACMANAGE_VERSION="${PACMANAGER_VERSION}")

# Copy the version file next to the executable so UpdateManager can read the
# running build's version at runtime.
add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD
    COMMAND ${CMAKE_COMMAND} -E copy
            ${CMAKE_CURRENT_SOURCE_DIR}/version
            $<TARGET_FILE_DIR:${PROJECT_NAME}>/version)

# Install
install(TARGETS ${PROJECT_NAME} DESTINATION bin)
install(FILES version DESTINATION bin)

# Ship the providers with the install so an installed app keeps its plugins:
# <prefix>/bin/plugins (next to the binary, first search path) and
# <prefix>/lib/PacManager/plugins (system-wide search path).
if(FWS_BUILD_FLATPAK_PLUGIN)
    install(FILES $<TARGET_FILE:flatpak-provider-plugin>
            DESTINATION bin/plugins)
    install(FILES $<TARGET_FILE:flatpak-provider-plugin>
            DESTINATION lib/PacManager/plugins)
endif()
if(FWS_BUILD_AUR_PLUGIN)
    install(FILES $<TARGET_FILE:aur-provider-plugin>
            DESTINATION bin/plugins)
    install(FILES $<TARGET_FILE:aur-provider-plugin>
            DESTINATION lib/PacManager/plugins)
endif()

# Desktop entry + icon so the installed app shows up in launchers
# (wofi, GNOME, KDE...). Icon goes to the hicolor theme, desktop file is
# patched with the actual install prefix at install time. The MimeType lines
# register the Flatpak file formats, which is what makes a file manager offer
# "Ouvrir avec PacManager" on a .flatpakref / .flatpakrepo / .flatpak; %U hands
# the selected file over on the command line.
install(FILES resources/icons/package.svg
        DESTINATION share/icons/hicolor/scalable/apps
        RENAME org.fws.PacManager.svg)

# Same route for the .fwspacm plugin packages, which the entry above does not
# cover: the Flatpak types are declared by flatpak itself, so Dolphin already
# knows them, but nothing declares ours. The XML gives the extension a MIME
# type (and the icon a name), mimeapps.list says which application opens it.
#
# update-mime-database is run at install time because the spec requires it: it
# is what merges the XML into the shared database the file managers read. It is
# a hard requirement for .fwspacm to be recognised at all, so a missing one
# fails the install rather than leaving a half-configured desktop behind.
install(FILES resources/mime/fws-pacmanager.xml
        DESTINATION share/mime/packages)
# Beside the desktop entry, which is the location XDG_DATA_DIRS/applications
# reads. No patching needed: it names the desktop entry, not an absolute path.
install(FILES resources/mime/mimeapps.list
        DESTINATION share/applications)
install(FILES resources/icons/plugin-package.svg
        DESTINATION share/icons/hicolor/scalable/apps
        RENAME application-vnd.fws.pacmanager.plugin-package.svg)
# Refreshing the database is a system-wide side effect, so it is skipped when
# installing into a staging root (DESTDIR set): the packager runs it against the
# real prefix once the package is deployed. That also means a packaging build
# never needs shared-mime-info installed on the build machine.
install(CODE "
    if(NOT \"\$ENV{DESTDIR}\" STREQUAL \"\")
        message(STATUS \"Skipping update-mime-database (DESTDIR is set)\")
    else()
        find_program(UPDATE_MIME_DATABASE update-mime-database)
        if(NOT UPDATE_MIME_DATABASE)
            message(FATAL_ERROR
                \"update-mime-database not found: install shared-mime-info, or \"
                \".fwspacm files will not be recognised by the desktop\")
        endif()
        execute_process(
            COMMAND \"\${UPDATE_MIME_DATABASE}\" \"\${CMAKE_INSTALL_PREFIX}/share/mime\"
            RESULT_VARIABLE MIME_RESULT
            OUTPUT_VARIABLE MIME_OUTPUT
            ERROR_VARIABLE MIME_OUTPUT)
        if(NOT MIME_RESULT EQUAL 0)
            message(FATAL_ERROR \"update-mime-database failed: \${MIME_OUTPUT}\")
        endif()
    endif()
")
install(CODE "
    set(DESKTOP_DIR \"\$ENV{DESTDIR}\${CMAKE_INSTALL_PREFIX}/share/applications\")
    file(MAKE_DIRECTORY \"\${DESKTOP_DIR}\")
    file(WRITE \"\${DESKTOP_DIR}/org.fws.PacManager.desktop\"
\"[Desktop Entry]
Type=Application
Name=PacManager
GenericName=Package Manager
Comment=Gestionnaire de paquets pour Arch Linux
Exec=${CMAKE_INSTALL_PREFIX}/bin/PacManager %U
Icon=org.fws.PacManager
Terminal=false
Categories=System;PackageManager;Qt;
MimeType=application/vnd.flatpak.ref;application/vnd.flatpak.repo;application/vnd.flatpak;application/vnd.fws.pacmanager.plugin-package;
StartupNotify=true
\")
    ")
install(DIRECTORY include/ DESTINATION include/${PROJECT_NAME})

# Tests
enable_testing()
add_executable(pacman-manager-test tests/pacman-manager.test.cpp src/pacman-manager.cpp)
target_include_directories(pacman-manager-test PRIVATE include)
add_test(NAME pacman-manager-test COMMAND pacman-manager-test)

add_executable(flatpak-manager-test tests/flatpak-manager.test.cpp
    plugins/flatpak-provider/flatpak-manager.cpp)
target_include_directories(flatpak-manager-test PRIVATE include plugins/flatpak-provider)
add_test(NAME flatpak-manager-test COMMAND flatpak-manager-test)

# Real end-to-end test of the Flatpak provider against the live flatpak CLI
# (installs and uninstalls a small app). Skipped when flatpak is missing.
add_executable(flatpak-integration-test tests/flatpak-integration.test.cpp
    plugins/flatpak-provider/flatpak-manager.cpp)
target_include_directories(flatpak-integration-test PRIVATE include plugins/flatpak-provider)
add_test(NAME flatpak-integration-test COMMAND flatpak-integration-test)

add_executable(package-utils-test tests/package-utils.test.cpp)
target_include_directories(package-utils-test PRIVATE include)
add_test(NAME package-utils-test COMMAND package-utils-test)

# ProgressTracker is pure logic (it only reads output lines), so it is tested
# without a package manager, a display or even Qt.
add_executable(progress-tracker-test tests/progress-tracker.test.cpp)
target_include_directories(progress-tracker-test PRIVATE include)
add_test(NAME progress-tracker-test COMMAND progress-tracker-test)

# PluginPackage: the .fwspacm format. The archives are built in the test itself
# (a stored and a deflated entry, so both compression methods are exercised),
# the file half runs in a temporary directory, and the settings go to a
# temporary INI too, so nothing touches the user's real plugin directory.
add_executable(plugin-package-test tests/plugin-package.test.cpp
    src/plugin-package.cpp src/zip-archive.cpp src/app-logging.cpp
    include/plugin-package.h include/zip-archive.h)
target_include_directories(plugin-package-test PRIVATE include)
target_link_libraries(plugin-package-test PRIVATE Qt6::Core ZLIB::ZLIB)
add_test(NAME plugin-package-test COMMAND plugin-package-test)

add_executable(aur-manager-test tests/aur-manager.test.cpp
    plugins/aur-provider/aur-manager.cpp)
target_include_directories(aur-manager-test PRIVATE include plugins/aur-provider)
add_test(NAME aur-manager-test COMMAND aur-manager-test)

# UpdateManager::isNewerVersion is pure logic, but the file also pulls in Qt
# Network, so the test links Core + Network (no display needed).
# The logic layer runs without a display: it is exercised on its own (no
# QtWidgets), which is exactly the guarantee the view/core split is for.
# The Q_OBJECT headers are listed explicitly so AUTOMOC generates their moc
# file for this target (same reason as update-manager-test below).
add_executable(app-core-test tests/app-core.test.cpp
    src/app-core.cpp src/workers.cpp src/pacman-manager.cpp
    src/plugin-manager.cpp src/history-manager.cpp src/update-manager.cpp
    src/plugin-package.cpp src/zip-archive.cpp
    src/app-logging.cpp src/log-manager.cpp src/app-settings.cpp
    include/app-core.h include/workers.h include/update-manager.h
    include/plugin-package.h include/zip-archive.h include/log-manager.h
    include/app-settings.h)
target_include_directories(app-core-test PRIVATE include)
target_link_libraries(app-core-test PRIVATE Qt6::Core Qt6::Network ZLIB::ZLIB)
target_compile_definitions(app-core-test PRIVATE
    FWSPACMANAGE_VERSION="${PACMANAGER_VERSION}")
add_test(NAME app-core-test COMMAND app-core-test)

# AppSettings: the whole preferences model, exercised against a temporary
# settings file. The static policy (what a block lasts, when it is in force, what
# a cap or a directory is worth) is pure and needs no clock.
add_executable(app-settings-test tests/app-settings.test.cpp
    src/app-settings.cpp src/log-manager.cpp include/app-settings.h
    include/log-manager.h)
target_include_directories(app-settings-test PRIVATE include)
target_link_libraries(app-settings-test PRIVATE Qt6::Core)
add_test(NAME app-settings-test COMMAND app-settings-test)

# ---- Translations ----
#
# The language setting loads Qt catalogues named pacmanager_<code>.qm, looked up
# at runtime next to the settings or next to the binary (see
# src/language-manager.cpp). Compiling the .ts sources into .qm needs Qt
# Linguist, which is not always installed: when it is missing the app simply
# runs untranslated, so the build must not depend on it.
find_package(Qt6 QUIET COMPONENTS LinguistTools)
if(Qt6LinguistTools_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/translations)
    file(GLOB PACMANAGER_TS_FILES ${CMAKE_CURRENT_SOURCE_DIR}/translations/*.ts)
    if(PACMANAGER_TS_FILES)
        qt_add_translation(PACMANAGER_QM_FILES ${PACMANAGER_TS_FILES})
        add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD
            COMMAND ${CMAKE_COMMAND} -E make_directory
                    $<TARGET_FILE_DIR:${PROJECT_NAME}>/translations
            COMMAND ${CMAKE_COMMAND} -E copy
                    ${PACMANAGER_QM_FILES}
                    $<TARGET_FILE_DIR:${PROJECT_NAME}>/translations/)
        install(FILES ${PACMANAGER_QM_FILES}
                DESTINATION bin/translations)
    endif()
endif()

add_executable(update-manager-test tests/update-manager.test.cpp
    src/update-manager.cpp src/app-logging.cpp include/update-manager.h)
target_include_directories(update-manager-test PRIVATE include)
target_link_libraries(update-manager-test PRIVATE Qt6::Core Qt6::Network)
target_compile_definitions(update-manager-test PRIVATE
    FWSPACMANAGE_VERSION="${PACMANAGER_VERSION}")
add_test(NAME update-manager-test COMMAND update-manager-test)

# ---- Plugins ----
#
# Flatpak ships as an external provider plugin (not compiled into the binary):
# the produced .so is copied next to the executable and discovered at runtime
# by PluginManager, so it can be updated or removed independently of the core
# app. It is built by default, so a plain `cmake -B build` yields a
# Flatpak-enabled app; disable with -DFWS_BUILD_FLATPAK_PLUGIN=OFF.
option(FWS_BUILD_FLATPAK_PLUGIN "Build the Flatpak provider plugin" ON)

# AUR provider plugin (yay/paru wrapper). Built by default like Flatpak;
# disable with -DFWS_BUILD_AUR_PLUGIN=OFF. Shows "Unavailable" in the Plugins
# page when neither yay nor paru is installed.
option(FWS_BUILD_AUR_PLUGIN "Build the AUR provider plugin" ON)

# Optional example external provider plugin. Demonstrates the plugin mechanism:
# the produced library is copied next to the executable and discovered at
# runtime by PluginManager (see the Plugins page).
option(FWS_BUILD_EXAMPLE_PLUGIN "Build the example external provider plugin" OFF)

# Optional example addon plugin: a non-provider extension (see
# plugins/example-addon) proving that plugins can be anything written in C++,
# not just package managers. Built next to the executable like any external
# plugin.
option(FWS_BUILD_EXAMPLE_ADDON "Build the example addon plugin" OFF)

if(FWS_BUILD_FLATPAK_PLUGIN)
    add_library(flatpak-provider-plugin MODULE
        plugins/flatpak-provider/flatpak-provider.cpp
        plugins/flatpak-provider/flatpak-manager.cpp)
    target_include_directories(flatpak-provider-plugin PRIVATE include plugins/flatpak-provider)
    set_target_properties(flatpak-provider-plugin PROPERTIES
        OUTPUT_NAME "flatpak-provider"
        CXX_STANDARD 17
        CXX_STANDARD_REQUIRED ON)
    add_custom_command(TARGET flatpak-provider-plugin POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E make_directory $<TARGET_FILE_DIR:PacManager>/plugins
        COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:flatpak-provider-plugin>
                $<TARGET_FILE_DIR:PacManager>/plugins/)
endif()

if(FWS_BUILD_AUR_PLUGIN)
    add_library(aur-provider-plugin MODULE
        plugins/aur-provider/aur-provider.cpp
        plugins/aur-provider/aur-manager.cpp)
    target_include_directories(aur-provider-plugin PRIVATE include plugins/aur-provider)
    set_target_properties(aur-provider-plugin PROPERTIES
        OUTPUT_NAME "aur-provider"
        CXX_STANDARD 17
        CXX_STANDARD_REQUIRED ON)
    add_custom_command(TARGET aur-provider-plugin POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E make_directory $<TARGET_FILE_DIR:PacManager>/plugins
        COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:aur-provider-plugin>
                $<TARGET_FILE_DIR:PacManager>/plugins/)
endif()

if(FWS_BUILD_EXAMPLE_PLUGIN)
    add_library(example-provider-plugin MODULE plugins/example-provider/example-provider.cpp)
    target_include_directories(example-provider-plugin PRIVATE include)
    set_target_properties(example-provider-plugin PROPERTIES
        OUTPUT_NAME "sample-provider"
        CXX_STANDARD 17
        CXX_STANDARD_REQUIRED ON)
    add_custom_command(TARGET example-provider-plugin POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E make_directory $<TARGET_FILE_DIR:PacManager>/plugins
        COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:example-provider-plugin>
                $<TARGET_FILE_DIR:PacManager>/plugins/)
endif()

if(FWS_BUILD_EXAMPLE_ADDON)
    add_library(example-addon-plugin MODULE plugins/example-addon/example-addon.cpp)
    target_include_directories(example-addon-plugin PRIVATE include)
    # The demo addon attaches Qt widgets, so it links the widget module like
    # the host application.
    target_link_libraries(example-addon-plugin PRIVATE Qt6::Widgets)
    set_target_properties(example-addon-plugin PROPERTIES
        OUTPUT_NAME "sample-addon"
        CXX_STANDARD 17
        CXX_STANDARD_REQUIRED ON)
    add_custom_command(TARGET example-addon-plugin POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E make_directory $<TARGET_FILE_DIR:PacManager>/plugins
        COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:example-addon-plugin>
                $<TARGET_FILE_DIR:PacManager>/plugins/)
endif()

# Plugin manager test: needs Qt (QSettings/QLibrary) and the example plugins
# built next to the test binary, so it is only enabled with both plugin
# options.
if(FWS_BUILD_EXAMPLE_PLUGIN AND FWS_BUILD_EXAMPLE_ADDON)
    add_executable(plugin-manager-test tests/plugin-manager.test.cpp
        src/plugin-manager.cpp src/pacman-manager.cpp src/app-logging.cpp
        plugins/flatpak-provider/flatpak-manager.cpp)
    target_include_directories(plugin-manager-test PRIVATE include plugins/flatpak-provider)
    # Qt6::Widgets is linked so the process can load the example addon, which
    # itself links the widget module.
    target_link_libraries(plugin-manager-test PRIVATE Qt6::Core Qt6::Widgets)
    add_dependencies(plugin-manager-test example-provider-plugin example-addon-plugin)
    add_custom_command(TARGET plugin-manager-test POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E make_directory
                $<TARGET_FILE_DIR:plugin-manager-test>/plugins
        COMMAND ${CMAKE_COMMAND} -E copy
                $<TARGET_FILE:example-provider-plugin>
                $<TARGET_FILE_DIR:plugin-manager-test>/plugins/
        COMMAND ${CMAKE_COMMAND} -E copy
                $<TARGET_FILE:example-addon-plugin>
                $<TARGET_FILE_DIR:plugin-manager-test>/plugins/)
    if(FWS_BUILD_FLATPAK_PLUGIN)
        target_compile_definitions(plugin-manager-test PRIVATE FWS_FLATPAK_PLUGIN_BUILT)
        add_dependencies(plugin-manager-test flatpak-provider-plugin)
        add_custom_command(TARGET plugin-manager-test POST_BUILD
            COMMAND ${CMAKE_COMMAND} -E copy
                    $<TARGET_FILE:flatpak-provider-plugin>
                    $<TARGET_FILE_DIR:plugin-manager-test>/plugins/)
    endif()
    add_test(NAME plugin-manager-test COMMAND plugin-manager-test)
endif()
