#!/bin/bash
# Copyright 2013 Monterey Bay Aquarium Research Institute, all rights reserved.
# Periodically try to synchronize with beach. 
# If ping returns from an AUV endpoint, do NOT sync with shore yet... don't want to
# to bog down cpu with multiple rsyncs.
# Presumes that radio to beach is on beforehand

if [ $# -lt 3 ]; then
  echo usage: syncIntervalSec beachIP auvIP [other auvIPs]
  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
beachIP=$2

# Skip to non-beach endpoint IPs
shift    # skip interval
shift    # skip beach IP

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

  # Check to see if any AUV endpoint is linked ; want to avoid multiple rsyncs, so
  # back off if AUV is within network range. 
  auvConnected=false
  for auvIP in "$@"
  do
      ping -c 3 -w 10 $auvIP
      if [ $? -eq 0 ]; then
      # AUV is linked - don't sync with beach yet; try again later
	  echo $auvIP is linked - do not sync with $beachIP yet, try again later
	  auvConnected=true
	  break
      fi
  done
  if $auvConnected; then
      sleep $intervalSec
      continue
  fi

  # Try to push/pull files to/from beach
  echo try to ping beach...
  success=false
  for i in {1..30}
  do
    echo Try \#$i to ping $beachIP
    ping -c 3 $beachIP
    if [ $? -eq 0 ]; then
      echo Able to ping $beachIP 
      success=true
      break
    fi
    sleep 1 
  done

  if $success; then
    /home/hotspot/script/syncer $beachIP $*
  else 
    echo No ping response from $beachIP
  fi

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

done

