#!/bin/sh
PATH=@binpath@${PATH+:}$PATH
_f=
args=
while [ $# -gt 0 ]; do
    case $1 in
        -f|--file)
            # Breaks if -f has no argument
            _f=$2
            shift 2
            ;;
        *) args="$args $1"
           shift
           ;;
    esac
done

set -- $args

if [ -z "$_f" -o ! -f "$_f" ]; then
    if [ -n "$LEDGER_FILE" ]; then
        _f=$LEDGER_FILE
    else
        while read -r f; do
            if [ "${f#*--file }" != "$f" ]; then
                _f=${f#*--file }
                break
            fi
            printf "Error: No journal file specified\n" >&2
            exit 1
        done <$HOME/.ledgerrc
    fi
fi

if [ "${_f%.gpg}" = "$_f" ]; then
    ledger "$@"
else
    gpg --no-tty --quiet -d "$_f" | ledger -f - "$@"
fi