#!/bin/env sh

declare -A actions
actions['Sync']="sync"
actions["Logout"]="logout"
actions["Lock"]="lock"

printSelection() {
  echo "$1"
  for key in "${!fruits[@]}"
  do
    echo "Action: $key"
  done
}

formattedIDs=$(echo "format:[NAME] ([USERNAME])" | nc -U /tmp/bitwarden-daemon.sock)

selectionList=$(echo "$formattedIDs" | jq 'keys | map("\(.)\n") | add' -r)
actionSelectionList=$(printf "Actions: %s\n" ${!actions[@]})
selection=$(printf "%s\n" "$selectionList" "$actionSelectionList" | anyrun --plugins libstdin.so)

echo "$selection"

if [[ $selection == '' ]]; then
  exit 0
fi

if [[ $selection == Actions:* ]]; then
  actionKey="${selection:9}"
  action="${actions[$actionKey]}"
  echo "Performing: $action"

  echo "$action:" | nc -U /tmp/bitwarden-daemon.sock
else
  id=$(echo "$formattedIDs" | jq ".[\"${selection}\"]" -r)
  echo "lookupPassword:$id" | nc -U /tmp/bitwarden-daemon.sock | wl-copy

  notify-send "Password copied" "Copied password for '$selection' to clipboard."
fi

exit 0;

