cmake_minimum_required(VERSION 3.16)
project(msn4lin VERSION 1.0 LANGUAGES CXX)

# Versión completa del programa y del paquete, sacada de git:
#   - en una etiqueta vX.Y.Z               ->  X.Y.Z
#   - N commits después de la última       ->  X.Y.Z+gitN.commit
#     (para apt, posterior a X.Y.Z y anterior a la siguiente)
# En el código fuente publicado (sin .git), git archive la deja escrita en el
# fichero VERSION (export-subst en .gitattributes). Si no hay ninguna de las
# dos, la del proyecto. -DMSN4LIN_VERSION=... la fija a mano.
set(MSN4LIN_VERSION "" CACHE STRING "Versión completa (programa y paquete); vacía: según git")
if(NOT MSN4LIN_VERSION)
  set(_describe "")
  if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/.git")
    find_package(Git QUIET)
    if(GIT_FOUND)
      execute_process(COMMAND "${GIT_EXECUTABLE}" describe --tags --match "v[0-9]*" --abbrev=7
                      WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
                      OUTPUT_VARIABLE _describe OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET)
      # Se vuelve a calcular al hacer un commit, cambiar de rama o crear una
      # etiqueta. Dónde están esos ficheros lo dice git: en un worktree o un
      # submódulo, .git no es una carpeta, y las ramas y etiquetas están en
      # la carpeta común.
      execute_process(COMMAND "${GIT_EXECUTABLE}" rev-parse --path-format=absolute --git-dir --git-common-dir
                      WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
                      OUTPUT_VARIABLE _dirs OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET)
      string(REPLACE "\n" ";" _dirs "${_dirs}")
      list(LENGTH _dirs _count)
      if(_count EQUAL 2)
        list(GET _dirs 0 _gitdir)
        list(GET _dirs 1 _common)
        set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${_gitdir}/HEAD")
        file(READ "${_gitdir}/HEAD" _head)
        if(_head MATCHES "^ref: ([^\n]+)" AND EXISTS "${_common}/${CMAKE_MATCH_1}")
          set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${_common}/${CMAKE_MATCH_1}")
        endif()
        foreach(_f packed-refs refs/tags)
          if(EXISTS "${_common}/${_f}")
            set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${_common}/${_f}")
          endif()
        endforeach()
      endif()
    endif()
  elseif(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/VERSION")
    file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/VERSION" _describe LIMIT_COUNT 1)
  endif()
  if(_describe MATCHES "^v([0-9][^-]*)-([0-9]+)-g([0-9a-f]+)$")
    set(MSN4LIN_VERSION "${CMAKE_MATCH_1}+git${CMAKE_MATCH_2}.${CMAKE_MATCH_3}")
  elseif(_describe MATCHES "^v([0-9][^-]*)$")
    set(MSN4LIN_VERSION "${CMAKE_MATCH_1}")
  else()
    set(MSN4LIN_VERSION "${PROJECT_VERSION}")
  endif()
endif()
message(STATUS "Versión de msn4lin: ${MSN4LIN_VERSION}")

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

find_package(Qt6 REQUIRED COMPONENTS Widgets Network Multimedia DBus)
find_package(Td REQUIRED)

# TDLib estático (dentro del programa): en macOS, y en los .deb de las
# distribuciones que no traen libtd-dev. Si no, la biblioteca del sistema.
option(MSN4LIN_STATIC_TDLIB "Enlazar TDLib estático (Td::TdJsonStatic)" OFF)
if(MSN4LIN_STATIC_TDLIB)
  set(MSN4LIN_TD Td::TdJsonStatic)
else()
  set(MSN4LIN_TD Td::TdJson)
endif()

# libqrencode: con pkg-config si lo hay; si no (macOS sin Homebrew), buscando
# la biblioteca y su cabecera en CMAKE_PREFIX_PATH.
find_package(PkgConfig QUIET)
if(PkgConfig_FOUND)
  pkg_check_modules(QRENCODE IMPORTED_TARGET libqrencode)
endif()
if(TARGET PkgConfig::QRENCODE)
  set(MSN4LIN_QRENCODE PkgConfig::QRENCODE)
else()
  find_library(QRENCODE_LIBRARY NAMES qrencode REQUIRED)
  find_path(QRENCODE_INCLUDE_DIR qrencode.h REQUIRED)
  add_library(msn4lin_qrencode INTERFACE)
  target_link_libraries(msn4lin_qrencode INTERFACE ${QRENCODE_LIBRARY})
  target_include_directories(msn4lin_qrencode INTERFACE ${QRENCODE_INCLUDE_DIR})
  set(MSN4LIN_QRENCODE msn4lin_qrencode)
endif()

# Credenciales de Telegram opcionales en el binario. Si no se dan, se leen de
# ~/.config/msn4lin/telegram.conf en tiempo de ejecución.
set(TG_API_ID "" CACHE STRING "api_id de Telegram (opcional)")
set(TG_API_HASH "" CACHE STRING "api_hash de Telegram (opcional)")

set(SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src)
# Skins, traducciones, iconos y lanzador: lo que se instala tal cual.
set(DATA_DIR ${CMAKE_CURRENT_SOURCE_DIR}/data)

# Todo salvo main.cpp va en una librería que usan el programa y las pruebas.
add_library(msn4lin_core STATIC
  ${SRC_DIR}/app/main_window.cpp
  ${SRC_DIR}/app/main_view.cpp
  ${SRC_DIR}/common/archive_lock.cpp
  ${SRC_DIR}/common/code_blocks.cpp
  ${SRC_DIR}/common/data_path.cpp
  ${SRC_DIR}/common/emoticons.cpp
  ${SRC_DIR}/common/language.cpp
  ${SRC_DIR}/common/markdown_table.cpp
  ${SRC_DIR}/common/settings.cpp
  ${SRC_DIR}/common/user_paths.cpp
  ${SRC_DIR}/desktop/screen_area.cpp
  ${SRC_DIR}/desktop/idle_detector.cpp
  ${SRC_DIR}/desktop/tray_icon.cpp
  ${SRC_DIR}/desktop/sounds.cpp
  ${SRC_DIR}/telegram/td_client.cpp
  ${SRC_DIR}/telegram/telegram_connection.cpp
  ${SRC_DIR}/telegram/telegram_config.cpp
  ${SRC_DIR}/ui/chat/chat_window.cpp
  ${SRC_DIR}/ui/chat/collage.cpp
  ${SRC_DIR}/ui/chat/image_viewer.cpp
  ${SRC_DIR}/ui/chat/message_view.cpp
  ${SRC_DIR}/ui/common/banner.cpp
  ${SRC_DIR}/ui/common/bring_to_front.cpp
  ${SRC_DIR}/ui/common/status_icon.cpp
  ${SRC_DIR}/ui/common/window_theme.cpp
  ${SRC_DIR}/ui/common/text_control.cpp
  ${SRC_DIR}/ui/common/text_points.cpp
  ${SRC_DIR}/ui/contactlist/my_status.cpp
  ${SRC_DIR}/ui/contactlist/contact_list.cpp
  ${SRC_DIR}/ui/dialogs/options_dialog.cpp
  ${SRC_DIR}/ui/dialogs/password_dialog.cpp
  ${SRC_DIR}/ui/dialogs/theme_page.cpp
  ${SRC_DIR}/ui/login/login_view.cpp
  ${SRC_DIR}/ui/notifications/notification.cpp
)
# Cada área en su carpeta; los #include siguen siendo por nombre de fichero.
target_include_directories(msn4lin_core PUBLIC
  ${SRC_DIR}/app
  ${SRC_DIR}/common
  ${SRC_DIR}/desktop
  ${SRC_DIR}/telegram
  ${SRC_DIR}/ui/chat
  ${SRC_DIR}/ui/common
  ${SRC_DIR}/ui/contactlist
  ${SRC_DIR}/ui/dialogs
  ${SRC_DIR}/ui/login
  ${SRC_DIR}/ui/notifications
)
target_link_libraries(msn4lin_core PUBLIC Qt6::Widgets Qt6::Network Qt6::Multimedia Qt6::DBus ${MSN4LIN_TD}
                      ${MSN4LIN_QRENCODE})
if(APPLE)
  # El tiempo sin teclado ni ratón (IdleDetector)
  target_link_libraries(msn4lin_core PUBLIC "-framework CoreGraphics")
endif()

if(TG_API_ID AND TG_API_HASH)
  target_compile_definitions(msn4lin_core PRIVATE TG_API_ID=${TG_API_ID} TG_API_HASH="${TG_API_HASH}")
endif()

add_executable(msn4lin ${SRC_DIR}/main.cpp)
# Windows: sin consola detrás, y con su icono.
if(WIN32)
  set_target_properties(msn4lin PROPERTIES WIN32_EXECUTABLE ON)
  target_sources(msn4lin PRIVATE ${SRC_DIR}/msn4lin.rc)
endif()
target_link_libraries(msn4lin PRIVATE msn4lin_core)
target_compile_definitions(msn4lin PRIVATE MSN4LIN_VERSION="${MSN4LIN_VERSION}")

# macOS: una aplicación (Msn4Lin.app). Los datos, las fuentes y Qt los mete
# ci/macos/package.sh dentro de Contents/Resources y Contents/Frameworks.
if(APPLE)
  set_target_properties(msn4lin PROPERTIES
    MACOSX_BUNDLE ON
    OUTPUT_NAME Msn4Lin
    MACOSX_BUNDLE_BUNDLE_NAME Msn4Lin
    MACOSX_BUNDLE_GUI_IDENTIFIER com.msn4lin.Msn4Lin
    MACOSX_BUNDLE_BUNDLE_VERSION "${MSN4LIN_VERSION}"
    MACOSX_BUNDLE_SHORT_VERSION_STRING "${MSN4LIN_VERSION}"
    MACOSX_BUNDLE_COPYRIGHT "GPL-3.0-or-later"
    MACOSX_BUNDLE_ICON_FILE msn4lin.icns)
endif()

# Para ejecutar desde el repositorio, el binario recuerda dónde están skins/ y
# translations/. Un paquete no debe llevar esa ruta: compílalo con
# -DMSN4LIN_PACKAGE=ON y buscará los datos solo en <prefijo>/share/msn4lin.
option(MSN4LIN_PACKAGE "Compilar para empaquetar (sin la ruta del código fuente)" OFF)
if(NOT MSN4LIN_PACKAGE)
  target_compile_definitions(msn4lin PRIVATE MSN4LIN_DATADIR="${DATA_DIR}")
endif()

# Pruebas automáticas:  ctest --test-dir build   (o ./msn4lin.sh test)
# (el código fuente publicado, msn4lin-X.Y.tar.gz, no lleva tests/: entonces no se compilan)
option(MSN4LIN_TESTS "Compilar las pruebas" ON)
if(MSN4LIN_TESTS AND NOT MSN4LIN_PACKAGE AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/CMakeLists.txt")
  find_package(Qt6 REQUIRED COMPONENTS Test)
  enable_testing()
  add_subdirectory(tests)
endif()

# ----------------------------------------------------------------------------
# Instalación:  cmake --install build [--prefix ~/.local]
#
#   bin/msn4lin
#   share/msn4lin/{skins,translations}   (main.cpp los busca en ../share/msn4lin)
#   share/applications/msn4lin.desktop
#   share/icons/hicolor/{16x16,32x32,64x64,128x128,256x256}/apps/msn4lin.png
include(GNUInstallDirs)

install(TARGETS msn4lin RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} BUNDLE DESTINATION .) # BUNDLE: la .app de macOS

install(DIRECTORY ${DATA_DIR}/skins
        DESTINATION ${CMAKE_INSTALL_DATADIR}/msn4lin)

install(DIRECTORY ${DATA_DIR}/translations/
        DESTINATION ${CMAKE_INSTALL_DATADIR}/msn4lin/translations
        FILES_MATCHING PATTERN "*.qm")

install(FILES ${DATA_DIR}/msn4lin.desktop
        DESTINATION ${CMAKE_INSTALL_DATADIR}/applications)

install(FILES ${DATA_DIR}/icons/lo16-app-msn4lin.png
        DESTINATION ${CMAKE_INSTALL_DATADIR}/icons/hicolor/16x16/apps
        RENAME msn4lin.png)
install(FILES ${DATA_DIR}/icons/lo32-app-msn4lin.png
        DESTINATION ${CMAKE_INSTALL_DATADIR}/icons/hicolor/32x32/apps
        RENAME msn4lin.png)
# Los grandes, el de 32 ampliado píxel a píxel (para el Dock, los menús de
# aplicaciones y las tiendas, que piden al menos 64).
foreach(size 64 128 256)
  install(FILES ${DATA_DIR}/icons/hi${size}-app-msn4lin.png
          DESTINATION ${CMAKE_INSTALL_DATADIR}/icons/hicolor/${size}x${size}/apps
          RENAME msn4lin.png)
endforeach()

# ----------------------------------------------------------------------------
# Paquete .deb:  ./msn4lin.sh deb
#   (equivale a: cmake -S . -B build-deb -DCMAKE_BUILD_TYPE=Release
#                      -DMSN4LIN_PACKAGE=ON && cmake --build build-deb
#                && cd build-deb && cpack)
#
# Las dependencias (Qt6, TDLib, libqrencode...) las calcula dpkg-shlibdeps a
# partir de las librerías que usa el binario. Las credenciales de Telegram no
# van en el paquete salvo que se compile con -DTG_API_ID/-DTG_API_HASH: cada
# usuario las pone en ~/.config/msn4lin/telegram.conf.
set(CPACK_GENERATOR "DEB")
set(CPACK_PACKAGE_NAME "msn4lin")
set(CPACK_PACKAGE_VERSION "${MSN4LIN_VERSION}")
set(CPACK_PACKAGE_VENDOR "Borja Sánchez Zamorano")
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Telegram client with the look of MSN Messenger")
set(CPACK_PACKAGE_DESCRIPTION
"Msn4Lin was born in 2002 as an MSN Messenger client for KDE. Ported to Qt 6,
it now connects to Telegram while keeping the contact list, conversation
windows, classic emoticons, pop-up notifications and skins of MSN Messenger.")
set(CPACK_PACKAGING_INSTALL_PREFIX "/usr")
set(CPACK_DEBIAN_FILE_NAME DEB-DEFAULT)
set(CPACK_DEBIAN_PACKAGE_MAINTAINER "Borja Sánchez Zamorano <borsanza@gmail.com>")
set(CPACK_DEBIAN_PACKAGE_SECTION "net")
set(CPACK_DEBIAN_PACKAGE_HOMEPAGE "https://www.msn4lin.com/")
set(CPACK_DEBIAN_PACKAGE_SHLIBDEPS ON)
set(CPACK_STRIP_FILES ON)
# La fuente de emojis es obligatoria: los que no tienen dibujo de MSN (💛, 🏠,
# banderas...) los pinta la fuente, y sin ella salen como un cuadrado. CPack la
# añade a las dependencias que calcula dpkg-shlibdeps.
set(CPACK_DEBIAN_PACKAGE_DEPENDS "fonts-noto-color-emoji, fonts-inter, fonts-dejavu-core")
# Traducciones de Qt (botones Aceptar/Cancelar...); apt las instala por defecto.
set(CPACK_DEBIAN_PACKAGE_RECOMMENDS "qt6-translations-l10n")
include(CPack)
