cmake_minimum_required(VERSION 3.20)

project(MiracleIRC
    VERSION 0.9.0
    DESCRIPTION "An mIRC-shaped IRC client for Linux"
    HOMEPAGE_URL "https://github.com/jonaz/miracleirc"
    LANGUAGES CXX)

# --- version ---------------------------------------------------------------
#
# project(VERSION) above is the single source of truth. Everything else here
# decorates it: a pre-release suffix while a version is being worked towards,
# and the commit the build came from.
#
# Semantic versioning, with the phases in the README as the release plan.
# Until a version is cut, every build calls itself "<version>-dev", which
# sorts before "<version>" in both semver and dpkg — an unreleased build must
# never look newer than the release it precedes.
set(MIRACLE_VERSION_PRERELEASE "dev"
    CACHE STRING "Pre-release suffix; empty for a release build")

# The build id and the build date are both resolved when CMake configures, so
# the tree is watched for the two files that change when HEAD moves —
# otherwise a build made after a commit would still claim the previous one.
set(MIRACLE_BUILD_ID "")
set(MIRACLE_BUILD_DATE "")
find_package(Git QUIET)
if(GIT_FOUND AND EXISTS "${PROJECT_SOURCE_DIR}/.git")
    execute_process(
        COMMAND "${GIT_EXECUTABLE}" describe --always --tags --abbrev=8
        WORKING_DIRECTORY "${PROJECT_SOURCE_DIR}"
        OUTPUT_VARIABLE MIRACLE_BUILD_ID
        OUTPUT_STRIP_TRAILING_WHITESPACE
        ERROR_QUIET)
    # The commit's own date, in UTC, as one sortable number (YYYYMMDDhhmmss).
    # Deliberately the commit date and not the wall clock: the same commit then
    # always produces the same version, so rebuilding it never manufactures a
    # new one for apt to chase, while a later commit always sorts newer.
    execute_process(
        COMMAND "${CMAKE_COMMAND}" -E env TZ=UTC
                "${GIT_EXECUTABLE}" show -s --format=%cd
                --date=format-local:%Y%m%d%H%M%S HEAD
        WORKING_DIRECTORY "${PROJECT_SOURCE_DIR}"
        OUTPUT_VARIABLE MIRACLE_BUILD_DATE
        OUTPUT_STRIP_TRAILING_WHITESPACE
        ERROR_QUIET)
    set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
        "${PROJECT_SOURCE_DIR}/.git/HEAD"
        "${PROJECT_SOURCE_DIR}/.git/index")
elseif(EXISTS "${PROJECT_SOURCE_DIR}/source-stamp.cmake")
    # A source tarball (packaging/make-source-tarball.sh) has no .git, so the
    # two values were written into it when it was made.
    include("${PROJECT_SOURCE_DIR}/source-stamp.cmake")
endif()

# project(VERSION) is the single source of truth; everything here decorates it.
#
# 0.1.0 lands with F4. Until it does every build calls itself "0.1.0-dev",
# which sorts before "0.1.0" in both semver and dpkg — an unreleased build
# must never look newer than the release it precedes.
#
# A dev build also carries its commit date, because without it every
# "0.1.0~dev" is the same version to apt, and Update Manager would never see a
# newer build as an upgrade. The date keeps the '~dev' that holds the build
# below 0.1.0, and adds a trailing number that only ever grows, so each dev
# build upgrades cleanly to the next and still yields to the release.
# MIRACLE_VERSION_SHORT is the version without the build date — "0.1.0-dev",
# the form to show where the date would only be noise, such as the QUIT line a
# departing client leaves in a channel.
if(MIRACLE_VERSION_PRERELEASE)
    set(MIRACLE_IS_RELEASE false)
    set(MIRACLE_VERSION_SHORT "${PROJECT_VERSION}-${MIRACLE_VERSION_PRERELEASE}")
    if(MIRACLE_BUILD_DATE)
        set(MIRACLE_VERSION
            "${PROJECT_VERSION}-${MIRACLE_VERSION_PRERELEASE}.${MIRACLE_BUILD_DATE}")
        set(MIRACLE_DEB_VERSION
            "${PROJECT_VERSION}~${MIRACLE_VERSION_PRERELEASE}${MIRACLE_BUILD_DATE}")
    else()
        # No git to date the build from — a bare source tree. Fall back to the
        # undated form rather than invent a date.
        set(MIRACLE_VERSION "${PROJECT_VERSION}-${MIRACLE_VERSION_PRERELEASE}")
        set(MIRACLE_DEB_VERSION "${PROJECT_VERSION}~${MIRACLE_VERSION_PRERELEASE}")
    endif()
else()
    set(MIRACLE_IS_RELEASE true)
    set(MIRACLE_VERSION_SHORT "${PROJECT_VERSION}")
    set(MIRACLE_VERSION "${PROJECT_VERSION}")
    set(MIRACLE_DEB_VERSION "${PROJECT_VERSION}")
endif()

if(MIRACLE_BUILD_ID)
    set(MIRACLE_VERSION_FULL "${MIRACLE_VERSION} (${MIRACLE_BUILD_ID})")
else()
    set(MIRACLE_VERSION_FULL "${MIRACLE_VERSION}")
endif()

message(STATUS "MiracleIRC ${MIRACLE_VERSION_FULL}")

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
    set(CMAKE_BUILD_TYPE Debug CACHE STRING "Build type" FORCE)
endif()

# On a phone there is only the mobile client to build: no widgets, no
# command-line client, and no test runner that could execute there.
if(ANDROID OR IOS)
    set(MIRACLE_ON_PHONE ON)
else()
    set(MIRACLE_ON_PHONE OFF)
endif()

if(MIRACLE_ON_PHONE)
    option(MIRACLE_BUILD_TESTS "Build the test suite" OFF)
else()
    option(MIRACLE_BUILD_TESTS "Build the test suite" ON)
endif()
option(MIRACLE_BUILD_QT "Build the Qt transport and applications" ON)
option(MIRACLE_BUILD_MOBILE "Build the Qt Quick mobile client on this platform too" OFF)
option(MIRACLE_WERROR "Treat compiler warnings as errors" OFF)

# Shared warning set, attached to every target we own. Kept as an INTERFACE
# target so third-party code we may vendor later does not inherit it.
add_library(miracle_warnings INTERFACE)
target_compile_options(miracle_warnings INTERFACE
    -Wall
    -Wextra
    -Wpedantic
    -Wshadow
    -Wnon-virtual-dtor
    -Wold-style-cast
    $<$<BOOL:${MIRACLE_WERROR}>:-Werror>)

# Qt targets get a slightly relaxed set: moc-generated sources and Qt's own
# headers trip -Wold-style-cast, which is not something we can fix and not
# worth suppressing case by case.
add_library(miracle_qt_warnings INTERFACE)
target_compile_options(miracle_qt_warnings INTERFACE
    -Wall
    -Wextra
    -Wpedantic
    -Wshadow
    -Wnon-virtual-dtor
    $<$<BOOL:${MIRACLE_WERROR}>:-Werror>)

add_subdirectory(libmiracle)

if(MIRACLE_BUILD_QT)
    set(CMAKE_AUTOMOC ON)
    add_subdirectory(libmiracle-net)
    if(NOT MIRACLE_ON_PHONE)
        add_subdirectory(libmiracle-gui)
        add_subdirectory(apps/miracle-cli)
        add_subdirectory(apps/miracle)
    endif()
    if(MIRACLE_ON_PHONE OR MIRACLE_BUILD_MOBILE)
        add_subdirectory(apps/miracle-mobile)
    endif()
endif()

if(MIRACLE_BUILD_TESTS)
    enable_testing()
    add_subdirectory(tests)
endif()

# --- installation ----------------------------------------------------------

include(GNUInstallDirs)

if(MIRACLE_BUILD_QT AND NOT MIRACLE_ON_PHONE)
    install(TARGETS miracle-app miracle-cli
        RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}")

    install(FILES assets/miracleirc.desktop
        DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/applications")

    # AppStream metadata, so Software Manager and GNOME Software show the app
    # under its proper name rather than the lower-case package name.
    install(FILES assets/io.github.jonaz.MiracleIRC.metainfo.xml
        DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/metainfo")

    # The whole hicolor tree at once: every size the SVG was rendered to,
    # plus the SVG itself for shells that would rather scale it themselves.
    install(DIRECTORY assets/icons/hicolor
        DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons")
endif()

# --- packaging -------------------------------------------------------------
#
# One package, built with `cpack -G DEB` from a Release build tree. The
# version comes from the same place everything else does; the Debian form of
# it is the one with '~' before the pre-release suffix.

set(MIRACLE_PACKAGE_MAINTAINER "jonaz <info@thern.io>"
    CACHE STRING "Debian maintainer field: Name <email>")

set(CPACK_PACKAGE_NAME "miracleirc")
set(CPACK_PACKAGE_VERSION "${MIRACLE_DEB_VERSION}")
# Leads with the display name, because this synopsis is the one human-readable
# line apt tools show beside the package: `apt show`, and Update Manager's row.
# The package is named `miracleirc` there — lower case, as Debian requires — so
# this line is the only place "Miracle IRC" can be read in those tools.
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Miracle IRC — an mIRC-shaped IRC client for Linux")
set(CPACK_PACKAGE_HOMEPAGE_URL "${PROJECT_HOMEPAGE_URL}")
set(CPACK_PACKAGE_CONTACT "${MIRACLE_PACKAGE_MAINTAINER}")
set(CPACK_RESOURCE_FILE_LICENSE "${PROJECT_SOURCE_DIR}/LICENSE")
set(CPACK_PACKAGE_FILE_NAME "miracleirc_${MIRACLE_DEB_VERSION}")
set(CPACK_STRIP_FILES ON)

set(CPACK_DEBIAN_PACKAGE_MAINTAINER "${MIRACLE_PACKAGE_MAINTAINER}")
set(CPACK_DEBIAN_PACKAGE_SECTION "net")
set(CPACK_DEBIAN_PACKAGE_PRIORITY "optional")
set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT")
# Let dpkg-shlibdeps read the binaries rather than maintaining a Qt version
# range by hand, which would be wrong the first time Qt moved.
set(CPACK_DEBIAN_PACKAGE_SHLIBDEPS ON)
# Recommended, not required: the client works without an ident daemon, it
# just gets a ~ in front of its user name. Settings offers to install this.
set(CPACK_DEBIAN_PACKAGE_RECOMMENDS "oidentd")
# One string, not a list: CMake joins a list with semicolons and they end up
# in the control file. The summary above is the first line already, so this
# is only the body.
set(CPACK_DEBIAN_PACKAGE_DESCRIPTION
"A feature clone of mIRC's interface, written in C++20 against Qt 6.
Nothing is decompiled or copied from mIRC: the behaviour is reimplemented
from the public protocol specifications and mIRC's own documentation, and
the icons are drawn from scratch.")

include(CPack)
