#!/bin/bash

### Lops watching $1 as long as it's been written in the last couple of minutes.
### As soon as that's not true, exits.  The point is to allow the PID of this
### script to be used as a --pid argument to tail --follow, so a tail that's
### stuffing an in-progress recording through eas-detect knows when to stop looking.

## Note that there's nothing tying our particular choice of deadness interval
## to that made by notice-new-files---the latter will continue to work fine
## no matter what we decide here.  But by the same token, there's no particular
## reason to make them different---except that, when the scheduler is very busy
## (often contending with the commflagger, and with low available RAM), I've seen
## the following scenario several times:  for a showing supposedly ending at nn:02,
## the file (apparently) stops being written at nn:01, while the scheduler thrashes
## away doing its reschedule when a recording ends, and then---sometimes as late as
## nn:07---the last update to the file happens, its mod-date becomes nn:02, and,
## since the file was declared dead 4 minutes ago and was then suddenly written to,
## we wind up noticing it as a -new- file and rescanning the entire thing!  This is
## a waste, since we already scanned all but the last minute of it, and can both
## cause us to emit a warning twice (if the recording had a problem earlier) and
## to also unnecessarliy load the backend (since mplayer will then run on the
## entire file at once, instead of incrementally, hence eating maybe 30%+ of the
## CPU for a couple minutes).  So, to avoid this misbehavior, we don't declare a
## file dead until at least 10 minutes have gone by without an update.  There's no
## downside to this (who cares if an extra empty file hangs around in the liveness
## directory for another few minutes?), and it avoids rescanning files.  After all,
## it's not as if we consume any runtime if we hold off on declaring a file dead---
## if nothing's currently writing to it, mplayer is just sitting there, waiting
## for input, because tail hasn't fed it any in a long time.  We can afford to have
## the extra half-dozen processes per recording sit around for another few minutes.

## The hair with dirname/basename is because "find foo -print" will complain
## "find: foo: No such file or directory" if foo doesn't exist, and this can
## happen if we're tailing a temporary file created by rsync which is then 
## renamed.  (Granted, in normal operation, that's not what we do!)  Doing it 
## the hard way below leads to no diagnostic.  (OTOH, it -also- means that a
## call where the file really isn't there will cause us to exit immediately,
## killing the eas-detector as well, so I'm not actually sure this is such a
## hot idea...)

dead=10		# Minutes.  Files older than this are declared dead.

dir=`dirname $1`
base=`basename $1`

while [ "`find $dir -maxdepth 1 -mindepth 1 -name $base -mmin -$dead -print`" != "" ]; do
  sleep 30
done

# End of file.
