#!/bin/bash

##
# Depends bw (bitwarden-cli), bw-unlock (personal script), xclip, jq
#
# Processes bw to allow for searching of passwords by website (and if multple logins per website, by account).
#
# By Solomon Laing (solomonlaing@pm.me)
# Date 2020-03-26
##

# get bw-session, will only work if owned by current user
if ! session=$(cat /tmp/bw-session)
then
    /home/solomon/.local/bin/bw-unlock
    session=$(cat /tmp/bw-session)
fi

items=$(bw list items --session "$session")
options=$(echo "$items" | jq ".[].name" | sed 's/"//g')

entry=$(echo "$options" | dmenu -i -p "Which entry?" $1)

if [ -z $entry ] 
then
    exit 0
fi

if ! password=$(bw get password "$entry" --session "$session")
then

    user_options=$(bw list items --search "$entry" --session "$session")

    # does not return array, not sure why yet
    # user_options=$(echo "$items" | jq '.[] | select(.name == "'"$entry"'") | .')

    user=$(echo "$user_options" | jq '.[].login.username' | dmenu -i -p "Which account?" $1 | sed 's/"//g')

    if [ -z $user ] 
    then
        exit 0; 
    fi

    pass=$(echo "$user_options" | jq '.[] | select(.login.username == "'"$user"'") | .login.password' | sed 's/"//g')

    echo "$pass" | xclip -sel clip

else
    echo "$password" | xclip -sel clip
fi

notify-send "password for $entry probably copied to clipbroad"
