#!/usr/bin/env bash

shopt -s nullglob globstar

prefix=${PASSWORD_STORE_DIR-~/.password-store}

while true
do

    unset password_files
    unset PASS
    unset FOLDER


    password_files=( "$prefix"/**/*.gpg )
    password_files=( "${password_files[@]#"$prefix"/}" )
    password_files=( "${password_files[@]%.gpg}" )
    password=$(printf '%s\n' "${password_files[@]}" \
                    | fzf -e -i $EXTRA --preview="gpg -d ${prefix}/{1}.gpg \
                        2> /dev/null ")

    [[ -n "$password" ]] || exit

    EXTRA="-q ${password#*/}"

    echo "$password" | fgrep -q '/' && FOLDER="${password%/*}/"

    echo "---------"
    echo "Selected: $password"
    PASS="$(pass "$password")"
    echo "Password: $(echo "$PASS" | head -1)"
    echo "$PASS" | grep -i "^username:"
    echo "$PASS" | grep -i "^email:"
    echo "$PASS" | grep -i "^url:"
    echo "---------"
    echo -n "[E]dit | [R]ename | [N]ew Password | [D]elete: "
    read

    case $REPLY in
        [eE]) echo "Editing $password."; pass edit "$password"; ;;
        [rR]) echo -n "Rename to: "; read -i "$FOLDER" -e REPLY; [ ! -z "$REPLY" ] && pass mv "$password" "$REPLY"; ;;
        [nN]) pass generate -i "$password" 22; ;;
        [dD]) pass rm "$password"; unset EXTRA; ;;
    esac
    echo "Updating ksh completions"
    ksh-update-completions

    echo
    echo "Press any key to continue"
    read

done
