#!/bin/bash
# Copyright 2013 Monterey Bay Aquarium Research Institute, all rights reserved.
# Periodically turn on specified radio link and try to synchronize files
# Note that powerOnCmd should perform all functions necessary to establish a
# tcp-ip link to linkIP - e.g. turn on radio power, start pppd, etc. Likewise
# powerOffCmd should shut down the link completely (e.g. stop pppd, turn off 
# power). NOTE: hotspot/script must be in your PATH variable.
if [ $# -lt 5 ]; then
  echo usage: powerOnCmd powerOffCmd syncIntervalSec linkIP IP1 IP2 IP3 ... IPn
  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

powerOnCmd=$1
shift
powerOffCmd=$1
shift
intervalSec=$1
shift

trap '{ echo "Turning radio OFF" ;  $powerOffCmd; exit 1; }' INT

if [ "$intervalSec" == "0" ]; then
  # Turn on power before starting loop
    echo Turning on radio before starting loop
     $powerOnCmd
fi

while [ 1 ]
do
  echo `date` - sync link
  if [ "$intervalSec" != "0" ]; then
    echo Turning radio on
     $powerOnCmd
  fi

  # Try to push/pull files
  syncer $*

  if [ "$intervalSec" != "0" ]; then
    echo Turning radio off
     $powerOffCmd
  fi

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

done

