#!/usr/bin/env bash
#
# MIT License.
# based on: https://git.sr.ht/~mlaparie/passfzf/tree/master/item/passfzf
#
# deps: pass-extension-otp (optional)

check_dep() {
  for dep; do
    if ! command -v "${dep}" 1>/dev/null; then
      printf "%s is not installed\n" "${dep}" 1>&2
      exit 1
    fi
  done
  unset dep
}

check_dep "pass" "fzf"

list_entries() {
  find "${HOME}/.password-store" -type f -name '*.gpg' -printf '%P\n' \
    | sed 's/\.gpg$//'
}

copy_username() {
  pass "$1" | grep '^login:' | cut -d' ' -f2 | wl-copy
}

while :; do
  clear
  selection=$(
    list_entries \
      | fzf \
        --bind "ctrl-b:execute(echo 'username' > /tmp/passarg)+accept" \
        --bind "ctrl-c:execute(echo 'password' > /tmp/passarg)+accept" \
        --bind "ctrl-e:execute(echo 'edit' > /tmp/passarg)+accept" \
        --bind "ctrl-a:execute(echo 'generate' > /tmp/passarg)+accept" \
        --bind "ctrl-m:execute(echo 'password' > /tmp/passarg)+accept" \
        --bind "ctrl-g:execute(echo 'quit' > /tmp/passarg)+abort" \
        --bind "esc:execute(echo 'quit' > /tmp/passarg)+abort" \
        --reverse \
        --gutter=' ' --color gutter:reverse \
        --color 'border:#000000' \
        --no-bold \
        --query "${tmp}" \
        --no-multi
  )

  # if [[ "${selection}" == *otp/* ]]; then
  if test "${selection}" = "*otp/*"; then
    otp=$(pass otp "${selection}")
    echo "${otp}" | wl-copy
    echo "${otp}"
    # Clear the clipboard
    sleep 8
    wl-copy -c
    exit
  fi

  if [ -f "/tmp/passarg" ]; then
    arg=$(cat /tmp/passarg)
    rm "/tmp/passarg"
  fi

  if [ -z "${selection+x}" ]; then
    clear
    case "${arg}" in
      username)
        copy_username "${selection}"
        tmp="${REPLY:=${selection}}"
        pass "${arg}" "${tmp}"
        tmp="${selection:=${tmp}}"
        ;;
      password)
        pass -c "${selection}"
        exit
        ;;
      generate)
        printf "New password Directory/Name: %s" "${selection}"
        if [ -n "${selection}" ]; then
          printf "\nPress Return to confirm or type new Directory/Name: "
        fi
        read -r REPLY
        tmp="${REPLY:=${selection}}"
        printf "Number of characters: "
        read -r
        pass "${arg}" --in-place "${tmp}" "${REPLY}" 2>/dev/null \
          || pass "${arg}" "${tmp}" "${REPLY}"
        tmp="${selection:=${tmp}}"
        printf "\nPress any key to continue. "
        read -rsn1
        ;;
      edit)
        pass "${arg}" "${selection}"
        ;;
      quit)
        exit
        ;;
    esac
  fi
done
