#!/usr/bin/env bash
set -eo pipefail

root="$HOME/.password-store"

list_accounts() {
  (cd "$root" && find -L . -name "*.gpg" | sed 's,^\./,,;s/\.gpg$//' | sort -n)
}

list_accounts_beginning_with_blank_page() {
  yes '' | head -n50
  list_accounts
}

do_type() {
  echo -n "$1" | ydotool type --file=-
}

get_passwd() {
  pass "$1" | head -n1
}

get_otp() {
  pass otp "$1"
}

get_field() {
  pass "$1" | grep "^$2: " | sed "s/$2: //"
}

account="$(list_accounts_beginning_with_blank_page | wofi -dip 'wofi-pass')"

test -n "$account" || exit

choices='password
username
url
otp'
choice="$(echo -n "$choices" | wofi -dp "$account")"

case "$choice" in
  password)
    passwd="$(get_passwd "$account")"
    do_type "$passwd"
    ;;
  username)
    username="$(get_field "$account" username)"
    do_type "$username"
    ;;
  url)
    url="$(get_field "$account" url)"
    do_type "$url"
    ;;
  otp)
    otp="$(get_otp "$account")"
    do_type "$otp"
    ;;
esac