#!/bin/sh
if [ -z "$1" ]
then  
        echo Usage: livesynch.sh [from] [to]  , i.e. ./livesynch.sh sentinel/ root@test.danbryg.dk:/srv/nginx/index/test/
        exit 65  
fi  

###################################

fromlocaltoserver(){
  while inotifywait -r -e modify,create,delete $fullname
  do
    rsync -zavr --delete --exclude *.idea --exclude *.git $fullname root@danbryg.dk:/srv/nginx/index/
  done
}

overwrite(){
  echo "copying from remote site"
  rsync -xavr --exclude *.git root@danbryg.dk:/srv/nginx/index/$dirname $localdir
}


###################################


echo "------------------------------------------"
echo "initial creation:"
echo "rsync --dirs $dirname root@danbryg.dk:/srv/nginx/index/"
echo "------------------------------------------"


echo "doublesync $1"

fullname=$(echo $1)
dirname=$(echo $1 | sed 's/.*\/\(.*\)/\1/g')
localdir=$(echo $1 | sed 's/\(.*\)\/.*/\1/g')
echo $dirname
echo $localdir

if [ -z "$dirname" ]
then
        echo cannot end with a slash
        exit 65
fi


changes=$(rsync -xavr  --dry-run --exclude *.git root@danbryg.dk:/srv/nginx/index/$dirname $localdir)
nochange=$(rsync -xavr  --dry-run --exclude *.git root@danbryg.dk:/srv/nginx/index/$dirname $localdir | wc -l)
echo "no of incomming changes: $nochange"


if [ $nochange -gt 5 ]
then
echo "the following files will be copied from server "
echo $changes
read -p "Continue (y/n)?" choice
case "$choice" in
  y|Y ) overwrite;;
  n|N ) exit 0;;
  * ) echo "invalid";;
esac

fi


fromlocaltoserver


