#!/bin/bash
src=$1
host=$2
user=$3
dst=$4
port=$5

/usr/bin/inotifywait -mrq --excludei ".*.log|.*.txt" --timefmt '%d/%m/%y %H:%M' --format '%T %w%f%e' -e modify,delete,create,attrib ${src} \
| while read files
  do
	  if [ -f "/opt/asterisk/scripts/astercc/astcc_rsynclist.conf" ]
	  then
		for curnode in `cat /opt/asterisk/scripts/astercc/astcc_rsynclist.conf`
		do	
			/usr/bin/rsync -aHL --delete --delay-updates --exclude=*.log  --exclude=*.txt --exclude=*.astercc --exclude=agentsxindesk.ctp --password-file=/etc/rsyncd/cluster.pass ${src} ${user}@${curnode}::${dst}
			#echo "${files} was rsynced"
			echo ${files} |grep -c "asterisk" &> /dev/null
			if [ $? = 1 ]
			then
				echo "${files} was rsynced to ${curnode}" >>/tmp/asterccrsync.log 2>&1
			else
				`ssh ${curnode} asterisk -rx "'core reload'"`
				echo "${files} was rsynced to ${curnode} and reload pbx" >>/tmp/asterccrsync.log 2>&1
			fi
			
		done
	  else
		/usr/bin/rsync -aHL --delete --delay-updates --exclude=*.log  --exclude=*.txt --exclude=*.astercc --exclude=agentsxindesk.ctp --password-file=/etc/rsyncd/${host}.pass ${src} ${user}@${host}::${dst}
		#echo "${files} was rsynced"
		echo ${files} |grep -c "asterisk" &> /dev/null
		if [ $? = 1 ]
		then
		echo "${files} was rsynced to $2" >>/tmp/asterccrsync.log 2>&1
		else
			`ssh -p${port} ${host} asterisk -rx "'core reload'"`
			echo "${files} was rsynced to $2 and reload pbx" >>/tmp/asterccrsync.log 2>&1
		fi		
	  fi  
  done

exit 0;
