#!/usr/bin/env bash

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

set -eo pipefail

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

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

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

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

  installed jq || return

  setting=$(
    kbs2 config dump \
      | jq --raw-output '.commands.ext."choose-pass"."notify-username" or false'
  )

  if [[ "${setting}" == "true" ]]; then
    username=$(kbs2 dump -j "${label}" | jq -r '.body.fields.username')
    osascript -e "display notification \"${label}: copied password for ${username}\" with title \"kbs2 choose-pass\""
  fi
}

labels=$(kbs2 list -k login)
label=$(choose <<< "${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}"
