#!/bin/bash
# Copyright 2013 Monterey Bay Aquarium Research Institute, all rights reserved.
# Pull outgoing and push incoming files from/to connected endpoint
# Assumes that endpoints are running rsync daemon configured to define 
# module "hotspot", with "path=/opt/hotspot" parameter.
# Returns 1 if any rsync errors encountered, else returns 0

if [ $# -eq 0 ]; then
  echo usage: connectedIP 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

rsyncPort="2001"
startingMsgFile=/tmp/begin-syncer
completedMsgFile=/tmp/end-syncer

startStatus=0
pullStatus=0
pushStatus=0
doneStatus=0

hotspotDir=/opt/hotspot

echo `date` - syncer starting 

# Connected IP is first argument
connEndpoint=$1
shift

# Remote prefix: userName@hotname::/moduleName
remotePrefix=hotspot@$connEndpoint::hotspot

cd $hotspotDir

opts="--timeout 60 -P -darzpu --copy-links --partial-dir=.rsync-partial --stats --port $rsyncPort --protocol=29"

# Create 'starting' message file and push to endpoint
rm -f $startingMsgFile >& /dev/null
touch $startingMsgFile
rsync $opts $startingMsgFile $remotePrefix/logs/ 2>&1 
startStatus=$?

# Pull from connected endpoint /outgoing directory to local Hotspot cache
# Ensure that destination directory exists
mkdir -p $hotspotDir/cache/$connEndpoint 
echo pull files from $connEndpoint to hotspot cache 
rsync $opts $remotePrefix/outgoing cache/$connEndpoint
pullStatus=$?
echo `date` - pull complete - status: $pullStatus

# Push files destined for connEndpoint from local Hotspot cache
while [ "$1" != "" ]; do
  if [ "$1" == $connEndpoint ]; then 
    # Don't need to push to ourself!
    shift
    continue
  fi

  echo check for pushed directory : cache/$1/outgoing/$connEndpoint

  if [ -e "cache/$1/outgoing/$connEndpoint" ]; then
    # Source directory exists - push it
    echo "push cached files from $1 to $connEndpoint" 
    rsync $opts cache/$1/outgoing/$connEndpoint/ $remotePrefix/incoming/$1 
    pushStatus=$?

  # Delete/move if successful?
  else
    echo cache/$1/outgoing/$connEndpoint not found
  fi

  shift
done

echo `date` ": done with push" 

# Create 'completed' message file and push to endpoint
rm -f $completedMsgFile >& /dev/null
touch $completedMsgFile
rsync $opts $completedMsgFile $remotePrefix/logs/ 
doneStatus=$?

echo 'done with pull/push' 

echo `date` syncer done.
if [ $startStatus -eq 0 ] && [ $pullStatus -eq 0 ] && [ $pushStatus == 0 ] && [ $doneStatus -eq 0 ]; then
  echo no rsync errors
  exit 0
else
  # Some rsync error occurred
  echo At least one rsync error
  exit 1
fi

