#!/usr/bin/env bash

# kbs2-dmenu-pass: List all kbs2 logins in dmenu, feed the selected one into the clipboard.

set -eo pipefail

[[ -n "${KBS2_SUBCOMMAND}" ]] \
  || { >&2 echo "Fatal: Not being run as a subcommand?"; exit 1; }

config="$(kbs2 config dump)"

function installed() {
  cmd=$(command -v "${1}")

  [[ -n  "${cmd}" ]] && [[ -f "${cmd}" ]]
  return ${?}
}

function maybe_notify_username() {
  label="${1}"

  installed jq || return

  setting=$(jq --raw-output '.commands.ext."dmenu-pass"."notify-username" or false' <<< "${config}")

  if [[ "${setting}" == "true" ]]; then
    username=$(kbs2 dump -j "${label}" | jq -r '.body.fields.username')
    notify-send "kbs2 dmenu-pass" "${label}: copied password for ${username}"
  fi
}

chooser=$(jq --raw-output '.commands.ext."dmenu-pass".chooser // "dmenu -p kbs2"' <<< "${config}")

labels=$(kbs2 list -k login)

# NOTE(ww): dmenu and similar tools exit with 1 when canceled; use `|| exit 0` here to ignore
# `set -e` so that we can check whether label is empty immediately below.
label=$(${chooser} <<< "${labels}" || exit 0)

# NOTE(ww): Exit with a success if the user canceled, to avoid nagging
# them with an error-hook.
[[ -z "${label}" ]] && exit 0

maybe_notify_username "${label}"

kbs2 pass -c "${label}"
