#!/bin/bash

# passmenu, for wayland
# depends: wtype, pass

shopt -s nullglob globstar

INSERTKEY="{{@@ key.insertMode @@}}"
#{%@@ if False @@%}#
INSERTKEY="i"
#{%@@ endif @@%}#

for m in "dmenu"  "bmenu"  "wofi" "wdmenu"; do
    command -v "$m" > /dev/null && dmenu="$m"
done

test -z "$dmenu" && exit 1
test "$dmenu" = "wofi" &&
    dmenu="wofi -d"

main() {

    prefix=${PASSWORD_STORE_DIR-~/.password-store}
    password_files=( "$prefix"/**/*.gpg )
    password_files=( "${password_files[@]#"$prefix"/}" )
    password_files=( "${password_files[@]%.gpg}" )

    entry=`printf '%s\n' "${password_files[@]}" | "$dmenu" -p "Password" $@`

    [ -n "$entry" ] || exit

    username=`pass show "$entry" 2>/dev/null | perl -ne 'print $1 if /^login: (.*)/'`
    password=`pass show "$entry" 2>/dev/null | head -n 1`

    action=`printf "Autotype\nUsername -> $username\nPassword" | "$dmenu" -p Action`

    case $action in
        Autotype)
            autotype
            ;;
        Username*)
            printf '%s' "$username" | wl-copy;;
        Password)
            printf '%s' "$password" | wl-copy;;
    esac

}

autotype(){

    curWindow=`swaymsg -t get_tree | jq -r '.. | select(.focused? == true).app_id'`
    if test "$curWindow" = "org.qutebrowser.qutebrowser"
    then
        wtype -s 100 -k escape
        wtype -s 100 "$INSERTKEY"
    fi

    wtype -s 100 "$username"
    wtype -s 100 -k tab
    wtype -s 100 "$password"

}

main
