#!/bin/bash
# Copyright 2013 Monterey Bay Aquarium Research Institute, all rights reserved.
# Periodically try to synchronize with Dorado. If pull from Dorado gets at
# least one file, then try to synchronize with shore. Presumes that Dorado
# Freewave and CDMA modem are ON beforehand.
# NOTE: hotspot/script must be in your PATH variable.
if [ $# -lt 3 ]; then
  echo usage: syncIntervalSec auvIP beachIP
  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


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

  # Try to push/pull files, check to see if any were transferred
  syncer $auvIP $beachIP | tee syncerOutput.txt
  awk -f /home/hotspot/script/checkXfer.awk syncerOutput.txt
  if [ $? -gt 0 ]; then
    # Got at least one transfer; try to sync with shore
    echo Try to sync with $beachIP
    ping -c 5 -w 10 $beachIP
    if [ $? -eq 0 ]; then
      syncer $beachIP $auvIP
    else
      echo no response from $beachIP
    fi
  else
    echo no files pulled from $auvIP
  fi

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

done

