#!/usr/bin/env bash

shopt -s nullglob globstar

typeit=0
if [[ $1 == "--type" ]]; then
	typeit=1
	shift
fi

prefix=${PASSWORD_STORE_DIR-~/.password-store}
password_files=( "$prefix"/**/*.gpg )
password_files=( "${password_files[@]#"$prefix"/}" )
password_files=( "${password_files[@]%.gpg}" )

entry=$(printf '%s\n' "${password_files[@]}" | sort | dmenu -l 7 -p "Pass" -i "$@")

[[ -n $entry ]] || exit

action=$(echo -e "Username\nPassword\nTOTP" | dmenu -p "Entry" -i )
case "$action" in
	Username)
		username=$(echo "$entry" | rev | cut -d"/" -f 1 | rev)
		echo "$username" | xclip -selection clipboard
		notify-send -a " Password Manager" "Username copied to clipboard";;
	Password)
		if [[ $typeit -eq 0 ]]; then
			pass show -c "$entry" 2>/dev/null
		else
			pass show "$entry" | { IFS= read -r pass; printf %s "$pass"; } |
				xdotool type --clearmodifiers --file -
		fi
		notify-send -a " Password Manager" "Password copied to clipboard";;
	TOTP)
		if [[ $typeit -eq 0 ]]; then
			pass otp -c "$entry" 2>/dev/null
		else
			pass otp "$entry" | { IFS= read -r pass; printf %s "$pass"; } |
				xdotool type --clearmodifiers --file -
		fi
		notify-send -a " Password Manager" "TOTP copied to clipboard";;
esac

