#!/bin/sh # quickLedger.sh: Quickly create a new entry for ledger # # Usage: quickLedger.sh [-t] [-f LEDGER_FILE] [-r REMOTE_LEDGER_FILE] [-c CURRENCY_SYMBOL] usageMessage='Usage: quickLedger.sh [-d] [-f LEDGER_FILE] [-r REMOTE_LEDGER_FILE] [-c CURRENCY_SYMBOL]' ledgerFile="$LEDGER_FILE" remoteLedgerFile="$REMOTE_LEDGER_FILE" currencySymbol='€' debug='' # $1: message # $2: exit code fatalError() { printf 'Error: %s' "$1" 1>&2 exit "$2" } organizeLines() { sort | uniq -c | sort -nr | sed 's/^\s*[0-9]* //' } getPayee() { grep '^\w' "$ledgerFile" | cut -d' ' -f2- | organizeLines | fzf --prompt 'Payee: ' --print-query --height 10 | tail -1 } # $1: fzf prompt getAccount() { grep '^\s' "$ledgerFile" | awk '{print $1}' | organizeLines | fzf --prompt "$1" --print-query --height 10 | tail -1 } getComment() { grep -o ';.*$' "$ledgerFile" | organizeLines | fzf --prompt "Comment: " --print-query --height 10 | tail -1 } getAmount() { read -r amount while ! echo "$amount" | grep -Eq '[0-9]+(\.[0-9][0-9])?'; do read -r amount done echo "$amount" | grep -Fq '.' || amount="${amount}.00" amount="${amount}${currencySymbol}" echo "$amount" } getTransaction() { printf '%s %s\n\t%s\t%s\t%s\n\t%s\n' "$date" "$payee" "$targetAccount" "$amount" "$comment" "$originAccount" } # Process options while getopts ':tf:r:c:' opt; do case $opt in 't' ) debug='y' ;; 'f' ) ledgerFile="$OPTARG" ;; 'r' ) remoteLedgerFile="$OPTARG" ;; 'c' ) currencySymbol="$OPTARG" ;; '?' ) printf '%s\n' "$usageMessage" exit 1 esac done shift $((OPTIND - 1)) [ -z "$remoteLedgerFile" ] && fatalError 'No remote ledger file. Set ledger file as REMOTE_LEDGER_FILE variable or with -r option.\n' 2 rsync -tz "$remoteLedgerFile" "$ledgerFile" || fatalError 'rsync failed.' 4 [ -z "$ledgerFile" ] && fatalError 'No ledger file. Set ledger file as LEDGER_FILE variable or with -f option.\n' 2 [ ! -f "$ledgerFile" ] && fatalError "No file [${ledgerFile}] found to use as ledger.\n" 3 targetAccount="$(getAccount 'Target account: ')" [ -z "$targetAccount" ] && exit 0 originAccount="$(getAccount 'Origin account: ')" [ -z "$originAccount" ] && exit 0 payee="$(getPayee)" printf 'Amount: ' amount="$(getAmount)" [ -z "$amount" ] && exit 0 printf '\n' comment="$(getComment)" date="$(date '+%Y/%m/%d')" getTransaction printf 'Correct? [Yn]: ' read -r correct [ "$correct" = "n" ] && exit 0 [ -n "$debug" ] && exit 0 printf '\n' >> "$ledgerFile" getTransaction >> "$ledgerFile" rsync -tz "$ledgerFile" "$remoteLedgerFile" || fatalError 'rsync failed.' 4