#!/bin/bash
#
# W. Trevor King, 2009.  Released into the public domain.
#
# Monitor an unfolding data directory and output a small png of the most
# recent unfolding curve
#
# usage: monfold <unfold_dir>
# e.g. : monfold ~/rsrch/data/unfold/20090331
#
# Requires the inotify-tools package if you're running Ubuntu
#
# Running something along the lines of
#   qiv --watch $OUTFILE # run qiv tracing the image file
# is a useful way to monitor the generated image without constantly
# grabbing the upper window.

if [ $# -ne 1 ]; then
    echo "usage: monfold <unfold_dir>"
    exit 1
fi

DATADIR="$1"
GPFILE="./monfold.gp"
DATALINK="./monfold.data"
OUTFILE="./monfold.png"
ACTION="scp $OUTFILE einstein:./public_html/rsrch/monfold.png" # upload to web

echo "set terminal png
set output '$OUTFILE'
plot '$DATALINK' using ((\$1/2**15-1)*10):((\$2/2**15-1)*10)" > "$GPFILE"

# The way output from the unfolding software works, we get a bunch of
#   YYYYMMDDHHMMSS_unfold
# files (which are what we want to be monitoring), along with some
#   YYYYMMDDHHMMSS_unfold_<blablabla>
# files with information we ignore.
#
# The files come out sequentially in time, but are written in multiple chunks
#   $ inotifywait -q -m -e CLOSE --exclude '.*unfold_.*' 20090331/
#   20090331/ CLOSE_WRITE,CLOSE 20090331163023_unfold
#   ...
#   20090331/ CLOSE_WRITE,CLOSE 20090331163023_unfold
#   20090331/ CLOSE_WRITE,CLOSE 20090331163044_unfold
#   ...
#   20090331/ CLOSE_WRITE,CLOSE 20090331163044_unfold
# Triggering on CLOSE isn't actually a good idea, since our monitoring
# activity involves reading the new file, which produces a bunch of
# CLOSE_NOWRITE,CLOSE events.  In the loop below we only look at
# CLOSE_WRITES, and we trigger off the transition from one file to the
# next, e.g. the 23->44 second example shown above, after which we
# process the 23 second data.

LASTFILE=""
# Multiple close events for the same file as data is written in blocks
while read LINE; do
    DIR=`echo "$LINE" | awk '{print  $1}'` # has trailing slash
    EVENT=`echo "$LINE" | awk '{print  $2}'`
    FILE=`echo "$LINE" | awk '{print  $3}'`
    if [ "$EVENT" != "CLOSE_WRITE,CLOSE" ]; then
	echo "Error (unexpected event '$EVENT'):"
	echo "$LINE"
	exit 1
    fi
    if [ "$FILE" != "$LASTFILE" ] && [ "$LASTFILE" != "" ]; then
	# We must have finished writing to $LASTFILE...
	echo "process $DIR$LASTFILE -> $OUTFILE"
	ln -s "$DIR$LASTFILE" "$DATALINK"
	gnuplot "$GPFILE"
	rm "$DATALINK"
	echo $ACTION
	$ACTION
    fi
    LASTFILE="$FILE"
done < <(inotifywait -q -m -e CLOSE_WRITE --exclude '.*unfold_.*' "$DATADIR")

rm "$GPFILE"
