#!/usr/bin/env sh
#
# fzfotp - get TOTP codes from yubikey with an interactive fuzzy search UI
# dependencies: fzf | ykman
#
# usage: fztotp [query]
#
# ---
# ykman <https://docs.yubico.com/software/yubikey/tools/ykman/intro.html>

set -eu

die() {
  printf '%s\n' "$*" >&2
  exit 1
}

select_code() {
  # prompt user to select a code (if necessary) and write it to stdout
  codes="$(ykman oath accounts code)" || exit
  test "${codes}" != "" || die "No TOTP codes found on key."
  echo "${codes}" \
    | fzf --height=10 --reverse \
      --select-1 --query="${*:-}" \
      --bind='enter:accept,esc:abort' \
    | awk '{ print $2 }'
}

otpprint() {
  printf '%s' "$1" | cut -d" " -f 1 | tr -d '\n' | pbcopy
}

code="$(select_code)"

if command -v pbcopy >/dev/null 2>&1; then
  otpprint "${code}"
  printf '%s\n' "Code copied to clipboard." >&2
fi

printf '%s' "${code}"
