#!/bin/bash
# pinentry-smart: use pinentry-curses normally, but fall back to pinentry-tty
# when another TUI (e.g. senpai) already owns the terminal/ncurses context.
#
# Detection: walk up the process tree. If we find a known TUI app before
# reaching a shell or login, assume the terminal is taken.

is_tui_parent() {
    local pid="$PPID"
    local tui_apps="senpai mutt neomutt irssi weechat ncmpcpp ranger vifm"
    for _ in $(seq 1 10); do
        [[ -z "$pid" || "$pid" -le 1 ]] && break
        local cmd
        cmd=$(ps -o comm= -p "$pid" 2>/dev/null)
        for app in $tui_apps; do
            [[ "$cmd" == "$app" ]] && return 0
        done
        pid=$(ps -o ppid= -p "$pid" 2>/dev/null | tr -d ' ')
    done
    return 1
}

if is_tui_parent; then
    exec /usr/bin/pinentry-tty "$@"
else
    exec /usr/bin/pinentry-curses "$@"
fi
