#! /usr/bin/zsh

pwdpath="/tmp/pwd.gpg"
pinpath="${XDG_DATA_HOME:-$HOME/.local/share}/pin.gpg"

if [ -f "$pwdpath" ]
then
    PIN="$(dmenupass "PIN")"
    export MASTERPW="$(gpg --batch --yes --passphrase "$PIN" --decrypt "$pwdpath" 2&>/dev/null)"
elif [ -f "$pinpath" ]
then
    export MASTERPW="$(dmenupass "Password")"
    PIN="$(gpg --batch --yes --passphrase "$MASTERPW" --decrypt "$pinpath" 2&>/dev/null)"
    echo "$MASTERPW" | gpg --symmetric --batch --yes --passphrase "$PIN" --output "$pwdpath"
else 
    export MASTERPW="$(dmenupass "Password")"
    PIN="$(dmenupass "PIN")"
    echo "$PIN" | gpg --symmetric --batch --yes --passphrase "$MASTERPW" --output "$pinpath"
    echo "$MASTERPW" | gpg --symmetric --batch --yes --passphrase "$PIN" --output "$pwdpath"
fi

[ -z "$MASTERPW" ] && exit 1;

choices="$(enpasscli -vault="$HOME/Documents/Enpass/Vaults/primary" -sort show 2>&1 | sed -n '/level=info/p')"

awkcommand='
    {
        if (length($3)) {
            $line = $2" ("$3")"; # If username exists wrap it in brackets
        } else {
            $line = $2; # Otherwise just show title
        }
        print $line;
    }
'

chosen="$(echo "$choices" | awk -F '\\s*(title|login|pass|cat\\.)\\s*:\\s*' "$awkcommand" | dmenu -i -ix -l 30)"

linenumber="$((chosen + 1))"

line="$(echo "$choices" | sed "${linenumber}q;d")"

# echo $line
echo $line | sed -n 's/.*\? pass : \(.\+\?\)"$/\1/p' | xclip -selection clipboard -i -loops 1

