# Copyright 2026 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2

EAPI=8

inherit desktop wrapper xdg optfeature

DESCRIPTION="A free and open source instant messaging and VoIP chat app built for friends, groups, and communities."
HOMEPAGE="https://fluxer.app"
SRC_URI="
    amd64? ( https://github.com/fluxerapp/fluxer/releases/download/fluxer-desktop-stable%40${PV}/Fluxer-${PV}-linux-x64.tar.gz -> ${P}-x64.tar.gz )
    arm64? ( https://github.com/fluxerapp/fluxer/releases/download/fluxer-desktop-stable%40${PV}/Fluxer-${PV}-linux-arm64.tar.gz -> ${P}-arm64.tar.gz )
"

S="${WORKDIR}"

LICENSE="AGPL-3+"
SLOT="0"
KEYWORDS="amd64 arm64"

RESTRICT="strip"
QA_PREBUILT=""

RDEPENDS="
    dev-libs/libfido2
    media-libs/alsa-lib
    media-libs/mesa
    sys-apps/util-linux
    x11-libs/libX11
"

src_install() {

    local dir_target="${S}"
    if [[ ! -f "${S}/fluxer" ]]; then
        local sub_dir=$(find "${S}" -maxdepth 1 -mindepth 1 -type d | head -n 1)
        if [[ -n "${sub_dir}" ]]; then
            dir_target="${sub_dir}"
        fi
    fi

    cd "${dir_target}" || die

    insinto /opt/fluxer
    doins -r *

    fperms +x /opt/fluxer/fluxer

    local desktop_file=$(find . -name "*.desktop" | head -n 1)
    local icon_file=$(find . -name "*.svg" -o -name "*.png" | head -n 1)

    if [[ -z "${icon_file}" ]]; then
        icon_file=$(find .type f \(name "*.png" -o -name "*.png" -o -name ".svg" \) | head -n 1)
    fi

    if [[ -n "${icon_file}" ]]; then
        newicon -s 256 "${icon_file}" fluxer.png
    fi

    if [[ -n "${desktop_file}" ]]; then
        sed -i \
            -e 's|^Exec=.*|Exec=/opt/fluxer/fluxer --ozone-platform-hint=auto|' \
            -e 's|^TryExec=.*|TryExec=/opt/fluxer/fluxer|' \
            -e 's|^Icon=.*|Icon=fluxer' \
            "${desktop_file}" || die
        domenu "${desktop_file}"
    else
        make_desktop_entry fluxer "Fluxer" fluxer "Network;InstantMessaging;"
    fi

    make_wrapper fluxer "/opt/fluxer/fluxer --ozone-platform-hint=auto"
}

pkg_postinst() {
    elog "By default Fluxer will make another application entry which"
	  elog "i am not sure what's causing to make another application entry on ~/.local/share/application"
	  elog "folder so just know i could not fix that!"
	  elog ""
    optfeature "desktop integration" x11-misc/xdg-utils
	  optfeature "system tray icon" dev-libs/libdbusmenu
	  optfeature "text-to-speech functionality" app-accessibility/speech-dispatcher
	  optfeature "Wayland portal protocol integration" sys-apps/xdg-desktop-portal

	  xdg_pkg_postinst
}