#!/bin/sh
# Simple alternative to pass(1) based on the work of Jay Scot:
# gopher://ams.jay.scot/0/phlog/016.txt
#
# Requires: xclip, gpg and md5
# Be sure to export PASSWORD_STORE
#
# Created by IanJ 2025 and released into the public domain without warranty or restriction.
# Use it at your peril!

PB_SECONDS=20 # Pasteboard cleared.

pw_copy()
{
       gpg -q --decrypt "${1}" | head -n1 | xclip -r
       echo "Clipboard will be cleared in $PB_SECONDS seconds." && $(sleep $PB_SECONDS) echo -n "" | xclip -silent &
}

pw_view()
{
       gpg -q --decrypt "${1}"
}

pw_new()
{
       [ -z "${1}" ] && echo "Please enter a filename." && exit

       dd if=/dev/random bs=1 count=32 2>/dev/null | md5 -b | gpg -e --default-recipient-self -o "${PASSWORD_STORE}/${1}.gpg" && pw_copy "${PASSWORD_STORE}/${1}.gpg"
}

passname="${2}"
[ -z ${passname} ] && passname="${1}"

res=$(find "${PASSWORD_STORE}" -type f -iname "*${passname}*")

if [ $( echo $res | wc -w ) = 1 ]; then
       if [ "${1}" = "-v" ]; then
               pw_view "${res}"
       else
               pw_copy "${res}"
       fi
else
       if [ "${1}" = "-n" ]; then
               pw_new "${2}"
       else
               for i in $res; do
                       basename $i .gpg
               done
       fi
fi