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

EAPI=8

PYTHON_COMPAT=( python3_{12..14} )
RUST_MIN_VER="1.98.0"

inherit git-r3 multiprocessing python-any-r1 rust toolchain-funcs xdg

DESCRIPTION="Independent web browser with its own web engine"
HOMEPAGE="https://ladybird.org/ https://github.com/LadybirdBrowser/ladybird"
EGIT_REPO_URI="https://github.com/LadybirdBrowser/ladybird.git"
EGIT_BRANCH="master"
# Includes the licenses of bundled runtime dependencies.
LICENSE="BSD-2 BSD MIT Apache-2.0 LGPL-2.1+ MPL-2.0 ISC ZLIB FTL Unicode-3.0"
SLOT="0"
KEYWORDS=""
IUSE="pipewire pulseaudio"
RESTRICT="test network-sandbox"

RDEPEND="
	>=dev-qt/qtbase-6.10:6[gui,widgets,network,dbus,X]
	>=dev-qt/qtpositioning-6.10:6
	dev-libs/glib:2
	media-libs/fontconfig
	media-libs/libglvnd
	pipewire? ( media-video/pipewire )
	pulseaudio? (
		|| (
			media-libs/libpulse
			media-sound/apulse[sdk]
		)
	)
	x11-libs/libdrm
	x11-libs/libxcb
	x11-libs/xcb-util-wm
	app-misc/ca-certificates
	media-fonts/liberation-fonts
	!www-client/ladybird-bin
"
DEPEND="${RDEPEND}"
BDEPEND="
	${PYTHON_DEPS}
	>=dev-build/cmake-3.30
	dev-build/ninja
	dev-build/autoconf
	dev-build/autoconf-archive
	dev-build/automake
	dev-build/libtool
	dev-lang/nasm
	dev-lang/perl
	dev-util/glslang
	dev-util/patchelf
	dev-vcs/git
	app-arch/unzip
	app-arch/zip
	net-misc/curl
	sys-libs/ncurses
	virtual/pkgconfig
	|| ( >=sys-devel/gcc-14 >=llvm-core/clang-19 )
"

pkg_setup() {
	python-any-r1_pkg_setup
	rust_pkg_setup
}

src_prepare() {
	# Avoid the GCC 14 Optional<Utf16View> / consteval linker failure.
	# The explicit ASCII conversion is equivalent for these string literals.
	local commands=Libraries/LibWeb/Editing/Commands.cpp
	if [[ -f ${commands} ]]; then
		sed -i -E \
			's/(set_the_selections_value\(document, CommandNames::[[:alnum:]_]+, )("[^"]+"sv)\);/\1Utf16View::from_ascii(\2));/' \
			"${commands}" || die
	fi

	# Rust 1.99 deprecated fetch_update() in favor of try_update().
	sed -i 's/\.fetch_update(/.try_update(/g' \
		AK/Rust/src/row_block.rs \
		AK/Rust/src/lib.rs || die

	# Keep the camera service, but use its NoCameras backend without PipeWire.
	if ! use pipewire; then
		local camera=Services/CameraServer/CMakeLists.txt
		if [[ -f ${camera} ]]; then
			sed -i -E \
				's/pkg_check_modules\(PIPEWIRE[[:space:]]+(REQUIRED[[:space:]]+)?IMPORTED_TARGET[[:space:]]+libpipewire-0\.3\)/set(PIPEWIRE_FOUND FALSE)/g' \
				"${camera}" || die
		fi
	fi

	if ! use pulseaudio; then
		sed -i 's/pkg_check_modules(PULSEAUDIO IMPORTED_TARGET libpulse)/set(PULSEAUDIO_FOUND FALSE)/' \
			Meta/CMake/audio.cmake || die
	fi

	# The upstream build driver configures CMake using the Release preset.
	# Keep bundled libraries in a private directory rather than /usr/lib*.
	sed -i '/"LADYBIRD_VCPKG_TYPE": "release"/i\        "CMAKE_INSTALL_PREFIX": "/opt/ladybird",\n        "CMAKE_INSTALL_LIBDIR": "lib",\n        "CMAKE_INSTALL_LIBEXECDIR": "libexec",\n        "BUILD_TESTING": "OFF",\n        "LADYBIRD_ENABLE_UPDATE_CHECK": "OFF",' \
		Meta/CMake/presets/CMakeBasePresets.json || die

	default
}

src_configure() {
	:
}

src_compile() {
	# vcpkg and the Rust build download pinned dependencies during the build.
	export CARGO_HOME="${WORKDIR}/cargo-home"
	export VCPKG_MAX_CONCURRENCY="$(makeopts_jobs)"
	"${PYTHON}" Meta/ladybird.py build --preset Release \
		--cc "$(tc-getCC)" --cxx "$(tc-getCXX)" \
		--jobs "$(makeopts_jobs)" || die
}

ladybird_fix_icu() {
	# Gentoo ICU disables symbol renaming, unlike vcpkg ICU. System Qt and
	# Ladybird must resolve their respective ICU ABIs independently.
	local root="${ED}/opt/ladybird"
	local component f candidate old new needed i
	local -a old_names=() new_names=() candidates=()

	for component in icudata icuuc icui18n; do
		candidates=()
		for candidate in "${root}/lib/lib${component}.so."*; do
			[[ -f ${candidate} && ! -L ${candidate} ]] && candidates+=( "${candidate}" )
		done
		[[ ${#candidates[@]} -eq 1 ]] ||
			die "Expected one real bundled ICU library for ${component}"
		f=${candidates[0]}
		old=$(patchelf --print-soname "${f}") || die
		[[ ${old} == lib${component}.so.* ]] || die "Unexpected ICU SONAME: ${old}"
		new="libladybird-${old#lib}"

		patchelf --set-soname "${new}" "${f}" || die
		mv -- "${f}" "${root}/lib/${new}" || die
		# Remove the old aliases, so Qt cannot accidentally load bundled ICU.
		for candidate in "${root}/lib/lib${component}.so"*; do
			[[ -L ${candidate} ]] || continue
			rm -- "${candidate}" || die
		done
		old_names+=( "${old}" )
		new_names+=( "${new}" )
	done

	find "${root}" -type f -print0 > "${T}/ladybird-installed-files" || die
	while IFS= read -r -d '' f; do
		needed=$(patchelf --print-needed "${f}" 2>/dev/null) || continue
		for i in "${!old_names[@]}"; do
			if grep -Fxq -- "${old_names[i]}" <<< "${needed}"; then
				patchelf --replace-needed "${old_names[i]}" "${new_names[i]}" "${f}" || die
			fi
		done
	done < "${T}/ladybird-installed-files"
}

ladybird_install_launcher() {
	# A session manager is not required to provide a private runtime directory.
	cat > "${T}/ladybird-launcher" <<'LAUNCHER' || die
#!/bin/sh

set -e

uid=$(id -u)

valid_runtime_dir()
{
    case $1 in
        /*) ;;
        *) return 1 ;;
    esac
    [ -d "$1" ] && [ ! -L "$1" ] && [ -w "$1" ] && [ -x "$1" ] &&
        [ "$(stat -c '%u:%a' -- "$1")" = "$uid:700" ]
}

if [ -z "${XDG_RUNTIME_DIR:-}" ]; then
    runtime=/run/user/$uid
    if ! valid_runtime_dir "$runtime"; then
        runtime=/tmp/ladybird-runtime-$uid
        mkdir -m 700 -- "$runtime" 2>/dev/null || true
        if ! valid_runtime_dir "$runtime"; then
            echo "ladybird: cannot create a safe runtime directory: $runtime" >&2
            exit 1
        fi
        echo "ladybird: XDG_RUNTIME_DIR is unset; using $runtime" >&2
    fi
    export XDG_RUNTIME_DIR="$runtime"
fi

exec /opt/ladybird/bin/ladybird "$@"
LAUNCHER

	rm -f -- "${ED}/usr/bin/ladybird" || die
	newbin "${T}/ladybird-launcher" ladybird

	# Route desktop and D-Bus activation through the same launcher.
	local f
	for f in "${ED}/usr/share/applications/"*.desktop \
		"${ED}/usr/share/dbus-1/services/"*.service; do
		[[ -f ${f} ]] || continue
		sed -i -E '/^Exec=/s@/opt/ladybird/bin/ladybird([[:space:]" ]|$)@/usr/bin/ladybird\1@g; /^TryExec=/s@/opt/ladybird/bin/ladybird$@/usr/bin/ladybird@' \
			"${f}" || die
	done
}

src_install() {
	local builddir="${S}/Build/release"
	DESTDIR="${D}" cmake --install "${builddir}" \
		--component ladybird_Runtime || die
	DESTDIR="${D}" cmake --install "${builddir}" \
		--component ladybird_SystemIntegration || die

	ladybird_fix_icu
	ladybird_install_launcher
}

pkg_postinst() {
	xdg_pkg_postinst

	elog "Ladybird uses XDG_RUNTIME_DIR for its IPC sockets."
	elog "If unset, the launcher uses /run/user/UID when available,"
	elog "or a private /tmp/ladybird-runtime-UID directory."
	elog "The fallback is not automatically removed at logout."
	elog "For session-wide runtime directory management without"
	elog "systemd or elogind, consider sys-auth/pam_xdg."
}