#!/bin/bash
#
# pput-gui - pput wrapper for file-manager right-click actions
#
# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Usage: pput-gui FILE [FILE...]
#
# Runs pput on the selection and reports the result as a desktop
# notification, since a file-manager click has no terminal to print to.

set -uo pipefail

notify() {  # notify(urgency, title, body)
    notify-send -a pput -u "$1" "$2" "$3" 2>/dev/null \
        || zenity --info --title="$2" --text="$3" 2>/dev/null \
        || true
}

[ $# -gt 0 ] || { notify critical "pput" "No files selected."; exit 2; }

# ponytail: pass(1) needs a gpg-agent with a usable pinentry. From a file
# manager there is no controlling terminal, so point at the GUI pinentry.
export GPG_TTY=""
export PINENTRY_USER_DATA="${PINENTRY_USER_DATA:-gui}"

out=$(pput "$@" 2>&1); rc=$?

ok=$(printf '%s\n' "$out" | grep -c '^OK ')
bad=$(printf '%s\n' "$out" | grep -cE '^(FAIL|TIMEOUT|skip) ')

if [ "$rc" -eq 0 ]; then
    notify normal "Paperless: $ok uploaded" "$out"
else
    notify critical "Paperless: $ok uploaded, $bad failed" "$out"
fi
exit $rc
