#!/bin/bash

set -x

log() {
    # echo "$@" >&2
    notify-send "Gopass form filler" "$*"
}

qute-command() {
    echo "$@" >> "$QUTE_FIFO"
}

send-key() {
    qute-command fake-key "$@"
}

insert-text() {
    qute-command insert-text "$@"
}

domain="$(echo "$QUTE_URL" | sed -E 's|^https?://||;s|/.*||')"

mapfile -t secrets < <(gopass find "$domain")

mode=${1:-"login-password"}

if (( ${#secrets[@]} > 1 ))
then
    secret="$(printf "%s\n" "${secrets[@]}" | rofi -dmenu)"
elif (( ${#secrets[@]} < 1 ))
then
    log "No secret found for domain $domain !"
    exit 0
else
    secret="${secrets[0]}"
fi

if [[ -z "$secret" ]]
then
    exit 0
fi

if [[ "$mode" = *login* ]] ; then insert-text "$(gopass show -o "$secret" login)" && sleep 0.1 ; fi
if [[ "$mode" = "login-password" ]] ; then send-key "<Tab>" ; fi
if [[ "$mode" = *password* ]] ; then insert-text "$(gopass show -o "$secret")" ; fi
if [[ "$mode" = "otp" ]] ; then insert-text "$(gopass otp -o "$secret")" ; fi
