#!/bin/bash

shopt -s nullglob globstar

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

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[@]}" | wdmenu -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" | wdmenu -p Action)

autotype(){
    if swaymsg -t get_inputs | grep -i colemak > /dev/null
    then
      swaymsg input \* xkb_layout 'us'
      restoreKeyLayout='us(colemak)'
    fi
    if [ $(swaymsg -t get_tree | jq -r '.. | select(.focused? == true).app_id') = "org.qutebrowser.qutebrowser" ]
    then
            ydotool --delay 1 key esc
            ydotool --delay 1 key "$INSERTKEY"
    fi
    ydotool type --delay 100 "$username"
    ydotool key tab
    ydotool type --delay 100 "$password"

    [ -n "$restoreKeyLayout" ] &&
        swaymsg input \* xkb_layout "$restoreKeyLayout"
}

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

