#!/bin/bash

shopt -s nullglob globstar

typeit=0
if [[ $1 == "--type" ]]; then
	typeit=1
	shift
fi
cmd=$(echo "list-files" | base64 -w 0)
password_files=($( echo ${cmd} | /usr/lib/qubes/qrexec-client-vm "$QUBES_PASS_DOMAIN" ruddo.PassQuery | sed 's/\..\{3\}$//'))
password=$(printf '%s\n' "${password_files[@]}" | dmenu "$@")

[[ -n $password ]] || exit

if [[ $typeit -eq 0 ]]; then
	qvm-pass "$password" 2>/dev/null | xsel -i -p && xsel -o -p | xsel -i -b
	sleep 10
	echo | xsel -i -p && xsel -o -p | xsel -i -b
else
	qvm-pass "$password" | { IFS= read -r pass; printf %s "$pass"; } |
		xdotool type --clearmodifiers --file -
fi
