#!/usr/bin/env bash

shopt -s nullglob globstar

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

if PASS=$(which gopass 2> /dev/null); then
    password_files="$($PASS ls --flat)"
elif PASS=$(which pass 2> /dev/null); then
    prefix=${PASSWORD_STORE_DIR-~/.password-store}
    password_files=( "$prefix"/**/*.gpg )
    password_files=( "${password_files[@]#"$prefix"/}" )
    password_files=( "${password_files[@]%.gpg}" )
else
    exit
fi

password=$(printf '%s\n' "${password_files[@]}" | $HOME/.config/i3/dmenu_cmd -p "Passwords" "$@")

[[ -n $password ]] || exit

if [[ $typeit -eq 0 ]]; then
	$PASS show -c "$password"
else
	xdotool - <<<"type --clearmodifiers -- $($PASS show "$password" | head -n 1)"
fi