#!/bin/sh
# unpack-lrauv-hotspot-logs.sh

#TODO# Would probably be more efficient to use python and/or inotify in the future.

FLOCK=/usr/bin/flock
LOCKDIR=/tmp

# ... only want one unpack or unserialize instance running at a time (for now)

#TODO make the locations below more portable
DATA_ROOT=/mbari/LRAUV
UNSERIALIZE=/mbari/LRAUV/Tools/linuxi64/unserialize
SLATEFILENAME="hotspot-Normal"

for vehicle in tethys daphne makai ahi aku opah whoidhs galene brizo pontus triton
do
  lck=$LOCKDIR/handle-lrauv-hotspot-logs.$vehicle.lck  # don't unpack during push or pull
  for d in `ls -d "$DATA_ROOT"/"$vehicle"/realtime/hotspotlogs/*`
  do
    unpack=false
    echo "checking for Normal-level logs in $d"
    if test -n "$(find $d -maxdepth 1 -name Normal* -print -quit)"	    
    then
      unpackedslate="$(find $d -maxdepth 1 -name $SLATEFILENAME.dir -print -quit)"
      if test $unpackedslate # string $unpackedslate is not NULL
      then
        echo "found $unpackedslate, checking for new Normal-level logs."
	newerslate="$(find $d -maxdepth 1 -name Normal* -newer $unpackedslate -print -quit)"
	if test $newerslate # string $newerslate is not NULL
	then
          unpack=true
	  echo "found $newerslate, newer than $unpackedslate -- will attempt to unpack"
        else
	  unpack=false
	  echo "did not find any Normal-level logs newer than $unpackedslate"
        fi
      else
        unpack=true
	newerslate="[first time]"
	echo "$SLATEFILENAME.dir does not exist in $d, but Normal-level logs do -- will attempt to unpack."
      fi

      if test "$unpack" == true
      then
	msg="unpacking slates up to $newerslate"
	cmd="nice $UNSERIALIZE -d -jmN -P Normal $d/$SLATEFILENAME"
        $FLOCK -n -e $lck -c "echo $msg && echo $cmd && $cmd"
#        $FLOCK -n -e $lck -c "echo DEBUG && echo $msg && echo $cmd"
        echo "unpacked Normal-level logs in $d"
      fi
    else
      echo "did not find Normal-level logs in $d" 
    fi
  done
done
