#!/usr/bin/env bash

shopt -s nullglob globstar


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

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

password=$(printf '%s\n' "${password_files[@]}" | "$dmenu" "$@")

[[ -n $password ]] || exit

password_contents=$(pass show "$password")

username=$(basename "$password")

if [[ "$password_contents" =~ "Username: " ]]; then
  username=$(echo "$password_contents" | grep "Username: " | cut -d' ' -f 2)
fi

echo "$username" | wl-copy -o -f

secret=$(echo "$password_contents" | head -n 1)

echo "$secret" | wl-copy -o -f
echo "" | wl-copy

if [[ "$password_contents" =~ "otpauth:/" ]]; then
  pass otp -c "$password"
fi
