#!/usr/bin/env bash

# This script checks to see if the user has configured a pinentry configuration in their user home or system-wide first.
# If neither is defined the script checks to see if the user is using KDE or GNOME and uses an appropriate pinentry client assuming the correct
# libs are present. If the user is using something else then it will use the gtk-2 one as a fallback, and ncurses as the ultimate fallback

# Run user-defined and site-defined pre-exec hooks.
[[ -r "${XDG_CONFIG_HOME:-$HOME/.config}"/pinentry/preexec ]] && \
    . "${XDG_CONFIG_HOME:-$HOME/.config}"/pinentry/preexec
[[ -r /etc/pinentry/preexec ]] && . /etc/pinentry/preexec

# Guess preferred backend based on environment.
backends=(curses tty)
if [[ -n "$DISPLAY" || -n "$WAYLAND_DISPLAY" ]]; then
	case "${XDG_CURRENT_DESKTOP,,}" in
	kde|lxqt)
		backends=(qt gnome3 gtk curses tty)
		;;
	*)
		backends=(gnome3 gtk qt curses tty)
		;;
	esac
fi

for backend in "${backends[@]}"
do
	lddout=$(ldd "/usr/bin/pinentry-$backend" 2>/dev/null) || continue
	[[ "$lddout" == *'not found'* ]] && continue
	exec "/usr/bin/pinentry-$backend" "$@"
done

exit 1
