#!/usr/bin/sh

# Automatically generated by plasma-browser-integration-flatpak-integrator

# SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
# SPDX-FileCopyrightText: 2024 Harald Sitter <sitter@kde.org>

set -eu

# Format arguments for gdbus based on whether it's Firefox (2 args) or Chrome (1 arg)
# See: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging#exchanging_messages
if [ $# -eq 2 ]; then
    # Firefox case - pack $1 and $2 into a single string
    args=$(printf "'%s', '%s'\n" "$1" "$2")
elif [ $# -eq 1 ]; then
    # Chrome case - format single argument
    args=$(printf "'%s'\n" "$1")
else
    echo "Error: Expected 1 (Chrome) or 2 (Firefox) arguments but got $#" >&2
    exit 1
fi

# The descriptor madness needs some explaining:
# We expect the forked gdbus to pick up three descriptors from us: 3, 4, and 5, respectively presenting our
# stdin, stdout, and stderr. This is because we need our io set to be distinct from gdbus' io set so gdbus doesn't write
# invalid data on the pipes and breaks stuff (e.g. it'd write the return value of the call but that is invalid nonesense to firefox).
#
# 3<&0: dup our input stdin (i.e. 0) to gdbus' fd 3
# 4>&1: dup our output stdout (i.e. 1) to gdbus' fd 4
# 5>&2: dup our output stderr (i.e. 2) to gdbus' fd 5
# 1>/dev/null: redirect gdbus' stdout to /dev/null because we don't care about it
#
# gdbus will then send 3,4,5 into dbus, effectively forwarding our descriptors. We meanwhile ignore their stdout.
gdbus call \
    --session \
    --dest org.kde.plasma.browser.integration \
    --object-path /org/kde/plasma/browser/integration \
    --method org.kde.plasma.browser.integration.FlatpakIntegrator.Link \
    ["$args"] 3 4 5 3<&0 4>&1 5>&2 1>/dev/null

sleep infinity
