#!/bin/bash
# Copyright 2013 Monterey Bay Aquarium Research Institute, all rights reserved.
# Periodically try to synchronize with AUV that is sometimes on surface. 
# If pull from AUV gets at least one file, then try to synchronize with shore.
# Presumes that AUV and shore radios are on beforehand.
if [ $# -lt 3 ]; then
  echo usage: syncIntervalSec auvIP beachIP [other endpoint IPs]
  exit 1
fi

if [ -z "$RSYNC_PASSWORD" ]; then
  echo "Must set environment variable RSYNC_PASSWORD to be password for user hotspot@endpoint"
  exit 1
fi

intervalSec=$1
auvIP=$2
beachIP=$3

# Move to unconnected endpoint arguments
shift    # skip interval
shift    # skip connected AUV IP


while [ 1 ]
do
  echo `date` - sync link

  # Try to push/pull files, check to see if any were transferred
  /home/hotspot/script/syncer $auvIP $* | tee syncerOutput.txt
  syncerStatus=$PIPESTATUS
  awk -f /home/hotspot/script/checkXfer.awk syncerOutput.txt
  if [ $? -gt 0 ] || [ $syncerStatus -eq 0 ]; then
    echo Pulled at least one file from $auvIP, or nothing new to pull - try sync with $beachIP
    # Try to sync with shore if we pulled at least one file from AUV, or
    # if we have good link with AUV but there are no files to pull at the moment
    echo Try to sync with $beachIP
    ping -c 5 -w 10 $beachIP
    if [ $? -eq 0 ]; then
       # Able to ping internet - now sync between beach and this AUV 
       # (ignore other AUVs in this sync; focus on just this one)
      /home/hotspot/script/syncer $beachIP $auvIP 
    else
      echo no response from $beachIP
    fi
  else
    echo Errors from sync with $auvIP - do not try sync with $beachIP yet
  fi

  # Wait for specified interval before trying again
  echo Wait $intervalSec seconds before next connection attempt
  sleep $intervalSec

done

