#!/bin/sh
# 2010 otto@bergerdata.de


SOURCE_DIR=/home/cluster/htdocs
DEST_DIR=/var/www/cluster/htdocs
HOSTS="192.168.100.6 192.168.100.7"
#HOSTS=`cat /home/cluster/nodes`

PROG_INOTIFYWAIT=/usr/bin/inotifywait
PROG_SSH=/usr/bin/ssh
PROG_SCP=/usr/bin/scp
SSH_USER=wwwdata


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

if [ -n "$1" ]
then
  SOURCE_DIR=$1
  DEST_DIR=$1
fi

if [ -n "$2" ]
then
  DEST_DIR=$2
fi

if [ -n "$3" ]
then
  SSH_USER=$3
fi

$PROG_INOTIFYWAIT -mrq --timefmt '%d/%m/%y %H:%M' --format '%e %T %w%f' \
  $SOURCE_DIR | while read event date time file; do

  SOURCE=${file/$SOURCE_DIR//}
  SOURCE=${SOURCE/\/\///}

  LOG=""

  case "$event" in

    "CREATE,ISDIR" )
      for HOST in $HOSTS; do
        LOG="creating directory ${DEST_DIR}${SOURCE}"
        $PROG_SSH -n ${SSH_USER}@${HOST} "mkdir -p ${DEST_DIR}${SOURCE}"
      done
      ;;

    "DELETE,ISDIR" )
      for HOST in $HOSTS; do
        LOG="deleting directory ${DEST_DIR}${SOURCE}"
        $PROG_SSH -n ${SSH_USER}@$HOST "rm -fr ${DEST_DIR}${SOURCE}"
      done
    ;;

    "DELETE" )
      for HOST in $HOSTS; do
        LOG="delete file ${DEST_DIR}${SOURCE}"
        $PROG_SSH -n ${SSH_USER}@$HOST "rm -f ${DEST_DIR}${SOURCE}"
      done
    ;;

    "CREATE" | "CLOSE_WRITE,CLOSE" )
      for HOST in $HOSTS; do
        LOG="copy file ${DEST_DIR}${SOURCE}"
        $PROG_SCP -pq $file ${SSH_USER}@$HOST:${DEST_DIR}${SOURCE}
      done
    ;;

    * )

    #LOG="NOT MATCHED: $event ON ${file}"
    ;;
  esac

  if [ -n "$LOG" ]
  then
    echo "${date} ${time} $LOG"
  fi

done


