#!/bin/sh

# pinentry-default - Script to change default pinentry interface
#
# Written in 2021 by Márcio Silva <coadde@hyperbola.info>
#
# To the extent possible under law, the author(s) have dedicated all copyright
# and related and neighboring rights to this software to the public domain
# worldwide. This software is distributed without any warranty.
#
# You should have received a copy of the CC0 Public Domain Dedication along
# with this software. If not, see
# <https://creativecommons.org/publicdomain/zero/1.0/>.

# user-defined DEFAULT_PINENTRY variable
if [ -r "${XDG_CONFIG_HOME:-$HOME/.config}/pinentry/preexec.conf" ]; then
  . "${XDG_CONFIG_HOME:-$HOME/.config}/pinentry/preexec.conf"
fi

# site-defined DEFAULT_PINENTRY variable
if [ -r '/etc/pinentry/preexec.conf' ]; then
  . '/etc/pinentry/preexec.conf'
fi

_exec='/usr/bin/pinentry'
_default="${_exec}-tty"

case "${DEFAULT_PINENTRY}" in
'curses')
  if [ -x "${_exec}-curses" ] && \
     [ ! -h "${_exec}-curses" ]; then
    "${_exec}-curses" "${@}"
  else
    "${_default}" "${@}"
  fi
  ;;
'emacs')
  if [ -x "${_exec}-emacs" ] && \
     [ ! -h "${_exec}-emacs" ]; then
    "${_exec}-emacs" "${@}"
  else
    "${_default}" "${@}"
  fi
  ;;
'fltk')
  if [ -x "${_exec}-fltk" ] && \
     [ ! -h "${_exec}-fltk" ]; then
    "${_exec}-fltk" "${@}"
  else
    "${_default}" "${@}"
  fi
  ;;
'gcr'|'gnome'|'gnome3'|'gnome-3'|'gtk'|'gtk3'|'gtk-3')
  if [ -x "${_exec}-gtk" ] && \
     [ ! -h "${_exec}-gtk" ]; then
    "${_exec}-gtk" "${@}"
  else
    "${_default}" "${@}"
  fi
  ;;
'gnome2'|'gnome-2'|'gtk2'|'gtk-2')
  if [ -x "${_exec}-gtk2" ] && \
     [ ! -h "${_exec}-gtk2" ]; then
    "${_exec}-gtk2" "${@}"
  else
    "${_default}" "${@}"
  fi
  ;;
'qt'|'qt5'|'qt-5')
  if [ -x "${_exec}-qt" ] && \
     [ ! -h "${_exec}-qt" ]; then
    "${_exec}-qt" "${@}"
  else
    "${_default}" "${@}"
  fi
  ;;
'bemenu')
  if [ -x "${_exec}-bemenu" ] && \
     [ ! -h "${_exec}-bemenu" ]; then
    "${_exec}-bemenu" "${@}"
  else
    "${_default}" "${@}"
  fi
  ;;
'tty'|*)
  "${_default}" "${@}"
  ;;
esac
unset _exec _tty DEFAULT_PINENTRY
