#!/bin/bash

# xsyncs $1 to all other sibling hosts specified in ~/.xs2siblings/siblings resp. /etc/xs2siblings
# this way ~/.xs2siblings/siblings resp. /etc/xs2siblings/siblings  may be shared, too
#
# it is possible to pass along xsync options as $2..., i.e. -n for dry run

if [ -z "$1" ] ; then
  echo "ERROR: No file or directory given to xsync 2 siblings."
  exit 1
fi

export SLF="/etc/xs2siblings/siblings"
test -e ~/.xs2siblings/siblings && SLF=~/.xs2siblings/siblings
if [ ! -f ${SLF} ] ; then
  echo "ERROR: No sibling list, i.e. no file ~/.xs2siblings/siblings or /etc/xs2siblings/siblings"
  exit 2
fi

SHN=$(hostname -s)
export SIBLINGS=$(cat ${SLF} |egrep -v '^\s*(#|;|$)' |egrep -vi "^${SHN}(\\.|$)" |sort |uniq)


if [ -z "$SIBLINGS" ] ; then
  echo "ERROR: No siblings specified in ${SLF}."
  exit 3
fi

#echo "Siblings are: $SIBLINGS"

export DIR="$1"
shift
export XSOPTS="$*"

for SIBLING in $SIBLINGS
do
  SIBLINGNAME=$(echo "$SIBLING" |cut -f1 -d':')
  SIBLINGPORT=$(echo "$SIBLING" |cut -f2 -d':')
  echo "INFO: Synching to $SIBLING ..."
  if [ "$SIBLINGPORT" = "$SIBLINGNAME" ] ; then
    #echo "DEBUG: Synching to $SIBLING without special ssh options ..."
    xsync $DIR $SIBLING: $XSOPTS
  else 
    #echo "DEBUG: Synching to $SIBLINGNAME with RSYNC_RSH='ssh -p $SIBLINGPORT' ..."
    RSYNC_RSH="ssh -p $SIBLINGPORT" xsync $DIR $SIBLINGNAME: $XSOPTS
  fi 
done

