#!/bin/sh

mode=$1
index=0

if [ -z "$mode" ]; then
	mode="eval"
fi

printf %s\\n 'message-info "Requesting password..."' >> "$QUTE_FIFO"
results=$(bw list items --session --url "$QUTE_CURRENT_URL")

query() {
	printf %s "$results" | jq "$1"
}

if [ "$(query length)" != 1 ]; then
	index=$(query ".[] | .name,.login.username" | tr -d '"' | awk '!(NR%2){print $0 " (" p ")"}{p=$0}' | rofi -dmenu -format i)
fi

password="$(query ".[${index}].login.password" | tr -d '"')"

case $mode in
	eval)
		username="$(query ".[${index}].login.username" | tr -d '"')"
		script=$(printf %s """\
let e = document.activeElement, \
	f = e.closest('form'), \
	p = !f || e.type === 'password' ? e : f.querySelector('input[type=password]'), \
	u = !f || e.type === 'email' || e.type === 'text' ? e : f.querySelector('input[type=email], input[name=email], input[name=username], input[name=user_name], input[name=user], input[autofocus]'), \
	F = (i, v) => { if(i) { i.value = v; return true } }, \
	su = F(u, USERNAME), \
	sp = F(p, PASSWORD); \
if(su && sp) { 'Login filled' } \
else if(su) { 'Username filled' } \
else if(sp) { 'Password filled' } \
else 'Unable to fill login info' \
""")
		command="jseval $(printf '{ let USERNAME="%s", PASSWORD="%s"; %s }' "$username" "$password" "$script" )"
		;;

	*)
		command="insert-text ${password}"
		;;
esac

printf %s\\n "$command" > "$QUTE_FIFO"
