#!/bin/sh
: ${startedDir:=/mnt/mmc/started}
cd $startedDir || exit
tailArgs=
defTailArgs='-c4000'  #characters
self=`basename $0`

mostRecent() {
#output the names of the most recent output files of those given
  for name; do
    for last in *_$name; do :; done
    echo $last
  done
}

quote() {
  for arg; do echo -n "'$arg' "; done
}

while :; do
  case "$1" in
    "")
      tail ${tailArgs:-$defTailArgs} `mostRecent '*'`
      exit
  ;;
    [^-]*) cmds=
      for cmd; do
        [ "$cmd" = '--' ] && {
          for n in $cmds 1; do
            shift  #consume cmds and --
          done
          eval `quote "$@"` `mostRecent $cmds` | tail ${tailArgs:-$defTailArgs}
          exit
        }
        cmds="$cmds $cmd"
      done
      tail ${tailArgs:-$defTailArgs} `mostRecent $@`
      exit
  ;;
    --)  shift #no cmd names specified, but there is a filter
      eval `quote "$@"` `mostRecent '*'` | tail ${tailArgs:-$defTailArgs}
      exit
  ;;
    --help)  cat <<END >&2
$self background command output -- 11/3/20 brent@mbari.org
Usage:
  $self {options} cmdName
or
  $self {options} cmdName -- filter filterArgs
cmdName is the name previously given to a background command.  If omitted,
$self pipes output of the most recently executed background command thru tail
Any options replace those passed to 'tail'  [default is tail $defTailArgs]
Environment Variable:
  startedDir=directory containing output files  [$startedDir]
Examples:
  $self             #outputs tail of last background command started
  $self onESPclient #outputs tail of last onESPclient command
  $self -1 onESPclient  #outputs just the last line
  $self onESPclient -- grep :dry  #outputs just the lines containing :dry
END
    exit 2
  esac
  tailArgs="$tailArgs $1"
  shift
done
