#!/bin/bash

which gpg 2>&1 >/dev/null || { echo "need gpg"; exit 1; }
which xsel 2>&1 >/dev/null || { echo "need xsel"; exit 1; }

passdir="$HOME/.gpgstore/"

if [ -z "$1" ]; then
    echo "Usage: $0 [git-cred] <category>/<component>"
    echo
    echo "if 'git-cred' is given, then only the pass: value will be output to stdout"
    echo "Categories and component are:"
    ( cd $passdir ; ls -FR --color )
    exit -1
fi

if [ "$1" == "git-cred" ]; then
    # git-credential mode
    # could get with action is done on git, through GIT_REFLOG_ACTION (like pull/push/etc)
    # and last arg to the git-credential wrapper is like 'store' for my case
    shift
    args=$1
    category=${args/\/*/}
    component=${args/*\//}
    echo protocol=https
    gpg --textmode -d $passdir/$category/$component 2>/dev/null | while read; do
        field=${REPLY/:*/}
        value=${REPLY/*: /}
        if [ "$field" == "pass" ]; then
            echo password=$value
        elif [ "$field" == "user" ]; then
            echo username=$value
        elif [ "$field" == "host" ]; then
            echo host=$value
        fi
    done
else
    args=$1
    category=${args/\/*/}
    component=${args/*\//}
    gpg --textmode -d $passdir/$category/$component 2>/dev/null | while read; do
        field=${REPLY/:*/}
        value=${REPLY/*: /}
        if [ "$field" != "pass" ]; then
            echo $REPLY
        elif [ "$field" == "pass" ]; then
            echo $value | xsel -i
            echo "pass: XXXXXX"
        fi
    done
fi
