#!/bin/sh

# watchledger - Run command whenever your ledger journal changes
#
# usage: watchledger [ command ]
#
# Monitor the timestamp of your LEDGER_FILE and run a shell command
# whenever it changes.  The command is always run at least once.
# Does not handle more than one journal file.


command=${1:-clear; ledger bal Assets Expenses Income Liabilities}

if [ -z "$LEDGER_FILE" -o ! -r "$LEDGER_FILE" ]; then
   echo "Bad LEDGER_FILE environment variable" 1>&2
   exit 1
fi

file=`basename $LEDGER_FILE`
dir=`dirname $LEDGER_FILE`
tmpdir=${TMPDIR:-/tmp}
tsfile=$tmpdir/watchledger.$$
sleepinterval=1

# Clean up timestamp file on signal
trap 'rm -f $tsfile; exit 0' 1 2 15

# Always run command at least once
if ! touch -t 197001010000 $tsfile; then
   echo "Could not write timestamp file" 1>&2
   exit 1
fi

while true; do
    count=`find $dir -name $file -newer $tsfile | wc -l`
    if [ $count -gt 0 ]; then
        # Journal file is newer than timestamp reference, so run command
        eval "$command"
        touch $tsfile
    fi
    sleep $sleepinterval
done

exit 0
