#!/usr/bin/env bash

shopt -s nullglob globstar

typeit=1
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)
		password=$(pass show "$entry")
		echo "$password" | xclip -selection clipboard
		echo "$password" | { IFS= read -r pass; printf %s "$pass"; } |
			xdotool type --clearmodifiers --file -
		notify-send -a " Password Manager" "Password copied to clipboard";;
	TOTP)
		otp=$(pass otp "$entry")
		echo "$otp" | xclip -selection clipboard
		echo "$otp" | { IFS= read -r pass; printf %s "$pass"; } |
			xdotool type --clearmodifiers --file -
		notify-send -a " Password Manager" "TOTP copied to clipboard";;
esac

