#!/bin/sh
#
# Djibian — sync the user's gpg public keys into Thunderbird's RNP keystore.
#
# Copyright © 2026 foopgp <info@foopgp.org>
# SPDX-License-Identifier: GPL-3.0-only
#
# Thunderbird ships an embedded RNP OpenPGP implementation with its own
# keystore (<profile>/pubring.gpg), separate from ~/.gnupg/. The pref
# mail.openpgp.fetch_pubkeys_from_gnupg only reaches gpg on demand for
# individual sign/verify/encrypt operations; the "OpenPGP Key Manager"
# UI only enumerates RNP's keystore. Without this sync the manager is
# empty even when ~/.gnupg/ is populated.
#
# Runs from XDG autostart at session start. Skipped silently when
# Thunderbird is already running (concurrent write would corrupt the
# RNP keystore).
#
# Note: this script does NOT install or symlink the Djibian referents
# vCard / address book. The referents have not been asked for their
# consent to be auto-injected into every Djibian user's Thunderbird;
# the .vcf is shipped under /usr/share/djibian/addressbooks/ for the
# user to import manually if they want it.

set -u

command -v rnpkeys >/dev/null 2>&1 || exit 0
command -v gpg     >/dev/null 2>&1 || exit 0

pgrep -u "$(id -u)" -x thunderbird >/dev/null 2>&1 && exit 0

for profile in "$HOME"/.thunderbird/*-default/ ; do
	[ -d "$profile" ] || continue
	[ -f "$profile/prefs.js" ] || continue
	gpg --export-options export-clean --export --armor 2>/dev/null \
		| rnpkeys --import-keys --homedir "$profile" - >/dev/null 2>&1 || :
done

exit 0
