#!/bin/sh

full=0
if [ "$1" = "--full" ]; then
	full=1
fi

if [ -n "$WAYLAND_DISPLAY" ]; then
	dmenu=dmenu-wl
	xdotool="ydotool type --file -"
elif [ -n "$DISPLAY" ]; then
	dmenu=dmenu
	xdotool="xdotool type --delay 15 --clearmodifiers --file -"
else
	echo "Error: No Wayland or X11 display detected" >&2
	exit 1
fi

prefix=${PASSWORD_STORE_DIR-~/.local/share/pass}
rprefix=$(printf "%s" $prefix | sed 's/\//\\\//g')
password_files=$(ls "$prefix"/*.gpg "$prefix"/*/*.gpg | sed 's/^'${rprefix}'\///g' | sed 's/\.gpg//g')
password=$(printf "%s\n" "${password_files}" | "$dmenu" -i -l 15 -m 0)

[ -n "$password" ] || exit

if [ $full -eq 1 ]; then
	id=$(printf "%s" "$password" | sed 's/.*___//')
	printf "%s\n" $id | { IFS= read -r pass; printf %s "$id"; } | $xdotool
	xdotool key Tab
	pass show "$password" | { IFS= read -r pass; printf %s "$pass"; } | $xdotool
	xdotool key Return
	exit
fi

pass show "$password" | { IFS= read -r pass; printf %s "$pass"; } | $xdotool