#!/usr/bin/bash
# SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
# SPDX-FileCopyrightText: 2025 Thomas Duckworth <tduck@filotimoproject.org>
#
# Configure the Firefox Flatpak: GTK accent colours, speech-dispatcher,
# the Plasma Browser Integration policy, and NVIDIA hardware decoding.
# The files go into the org.mozilla.firefox.systemconfig extension
# directory, which Firefox reads as its system defaults.

set -eu

app=org.mozilla.firefox
if ! flatpak info --system "$app" >/dev/null 2>&1; then
    echo "The Firefox Flatpak is not installed." >&2
    exit 1
fi

# --show-runtime prints the ref (org.freedesktop.Platform/x86_64/25.08).
# The "Runtime:" label in the full output is translated, and services
# run with the system locale.
arch=$(flatpak info --system --show-runtime "$app" | cut -d/ -f2)
if [[ -z $arch ]]; then
    arch=$(flatpak --default-arch)
fi
config=/usr/share/atropos/firefox-config
ext=/var/lib/flatpak/extension/$app.systemconfig/$arch/stable
# Where an empty architecture put these files. Firefox never read them.
rm -rf "/var/lib/flatpak/extension/$app.systemconfig/stable"

flatpak override --system "$app" \
    --filesystem=xdg-config/gtk-3.0:ro \
    --filesystem=xdg-run/speech-dispatcher:ro

install -d "$ext/defaults/pref" "$ext/policies"
install -m 0644 "$config/00-atropos-default.js" "$ext/defaults/pref/00-atropos-default.js"
# Forcing hardware decoding helps NVIDIA and can break other GPUs.
if nvidia-smi >/dev/null 2>&1; then
    install -m 0644 "$config/01-atropos-nvidia-hw-decode.js" "$ext/defaults/pref/01-atropos-nvidia-hw-decode.js"
else
    rm -f "$ext/defaults/pref/01-atropos-nvidia-hw-decode.js"
fi
# Installs Plasma Browser Integration. Firefox then says it is managed
# by an organization; that is the cost of a policy file.
install -m 0644 "$config/policies.json" "$ext/policies/policies.json"
