#!/bin/sh
# push-lrauv-logs.sh
#
# This script sorts and pushes LRAUV logs to deployment directories sorted by year, 
# as defined in `.dlist` files. To monitor progress and/or debug, use `tail` on the 
# log file, e.g., :
#
#     [tethysadmin@tethysdata ~]$ tail -f /tmp/push-lrauv-logs.tethys.log
#

SSH=/usr/bin/ssh
SED=/bin/sed
FLOCK=/usr/bin/flock
LOCKDIR=/tmp
LOGDIR=/tmp

RSYNC=/usr/bin/rsync 
RSYNC_OPT="-rvh --times"

DATA_ROOT=/mbari/LRAUV

#TODO there is almost definitely a better way to do the task below
# 2016 2015 2014 2013 2012 2011 2010
for year in 2017 2018 2019 2020 2021 2022 2023  
do
  for vehicle in tethys daphne makai ahi aku opah whoidhs galene brizo pontus triton
  do
    lck=$LOCKDIR/handle-lrauv-logs.$vehicle.lck
    log=$LOGDIR/push-lrauv-logs.$vehicle.log
    dlists=$DATA_ROOT/$vehicle/missionlogs/$year/*.dlist
    for dlist in $dlists
    do
      # remove leading tabs & spaces in dlist
      $SED --in-place 's/^[[:blank:]]\+//' $dlist
      # remove trailing tabs & spaces in dlist
      $SED --in-place 's/[[:blank:]]\+[[:cntrl:]]\+$//' $dlist
      # get the deployment designation
      deployment=`basename "$dlist" .dlist`
      # define source and destination directories
      src="$DATA_ROOT/$vehicle/missionlogs/tmp/Logs"
      dst="$DATA_ROOT/$vehicle/missionlogs/$year/$deployment"
      # initialize directory tree up to destination (if necessary)
      mkdir -p $dst
      # define the rsync command
      rcmd="nice $RSYNC $RSYNC_OPT --files-from=$dlist $src $dst &>> $log"
      # tell me what the rsync command is
      echo $rcmd
      # truncate the last rsync log and reinitialize with the command
      echo $rcmd > $log
      # execute the rsync command under a nonblocking exclusive file lock
      $FLOCK -n -e $lck -c "$rcmd"
    done
  done
done
