include_guard(GLOBAL)

include(GNUInstallDirs)

if(UNIX AND NOT APPLE)
    set(_qemby_runtime_install_dir "${CMAKE_INSTALL_BINDIR}")
    if(QEMBY_RUNTIME_LIB_SUBDIR)
        set(_qemby_runtime_install_dir
            "${CMAKE_INSTALL_LIBDIR}/${QEMBY_RUNTIME_LIB_SUBDIR}")
    endif()

    foreach(_qemby_runtime_target IN ITEMS qEmbyApp qEmbyCore QWKCore QWKWidgets)
        if(TARGET "${_qemby_runtime_target}")
            set_target_properties("${_qemby_runtime_target}" PROPERTIES
                INSTALL_RPATH "$ORIGIN"
            )
        endif()
    endforeach()

    set(_qemby_qwk_install_targets)
    foreach(_qemby_qwk_target IN ITEMS QWKCore QWKWidgets)
        if(TARGET "${_qemby_qwk_target}")
            list(APPEND _qemby_qwk_install_targets "${_qemby_qwk_target}")
        endif()
    endforeach()

    if(_qemby_qwk_install_targets)
        install(TARGETS ${_qemby_qwk_install_targets}
            LIBRARY DESTINATION "${_qemby_runtime_install_dir}"
            RUNTIME DESTINATION "${_qemby_runtime_install_dir}"
            ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}"
        )
    endif()

    if(QEMBY_RUNTIME_LIB_SUBDIR)
        set(_qemby_launcher_exec
            "${CMAKE_INSTALL_LIBDIR}/${QEMBY_RUNTIME_LIB_SUBDIR}/qEmbyApp")
    else()
        set(_qemby_launcher_exec "${CMAKE_INSTALL_BINDIR}/qEmbyApp")
    endif()

    set(_qemby_launcher "${CMAKE_CURRENT_BINARY_DIR}/qemby")
    file(WRITE "${_qemby_launcher}"
        "#!/bin/sh\n"
        "prefix_dir=$(CDPATH= cd -- \"$(dirname -- \"$0\")/..\" && pwd)\n"
        "exec \"$prefix_dir/${_qemby_launcher_exec}\" \"$@\"\n"
    )
    install(PROGRAMS "${_qemby_launcher}"
        DESTINATION "${CMAKE_INSTALL_BINDIR}"
    )

    set(_qemby_desktop_file "${CMAKE_CURRENT_BINARY_DIR}/qemby.desktop")
    file(WRITE "${_qemby_desktop_file}"
        "[Desktop Entry]\n"
        "Type=Application\n"
        "Name=qEmby\n"
        "Comment=Desktop client for Emby and Jellyfin media servers\n"
        "Exec=qemby\n"
        "Icon=qemby\n"
        "Terminal=false\n"
        "Categories=AudioVideo;Video;Player;\n"
    )
    install(FILES "${_qemby_desktop_file}"
        DESTINATION "${CMAKE_INSTALL_DATADIR}/applications"
    )

    install(FILES "${CMAKE_SOURCE_DIR}/src/qEmbyApp/resources/svg/qemby_logo.svg"
        DESTINATION "${CMAKE_INSTALL_DATADIR}/icons/hicolor/scalable/apps"
        RENAME qemby.svg
    )
endif()

set(CPACK_PACKAGE_NAME "${PROJECT_NAME}")
set(CPACK_PACKAGE_VERSION "${PROJECT_VERSION}")
set(CPACK_PACKAGE_VENDOR "qEmby")

include(CPack)
