#!/bin/bash

# This script will monitor an rsync session, and restart it if it is interrupted
# in any way.
#
# By Eugenio Diaz - mailto:getnito@yahoo.com
# Released under the GNU GPL copyleft License, http://www.fsf.org
#

#
# Parameters
#

IDELAY='2m'
WDELAY='5m'
RDELAY='5m'
DIR='/home/ftp/pub/linux/.'
ISTATUS=`netstat -i|grep ppp0`
RSTATUS=`ps ax|grep rsync`

echo
echo "Initial delay before starting monitoring cycle: $IDELAY"
echo "Monitoring cycle period: $WDELAY"
echo "Restart delay: $RDELAY"
echo
echo "Spawninig: $1"
echo

$1 &
sleep $IDELAY
echo
echo "Starting monitor."
echo

while true
do

   if [ "$ISTATUS" = "" ]; then

      echo "Not connected, exiting ..."
	  exit 1

   elif [ "$RSTATUS" = "" ]; then

      echo "Rsync no longer running. Mirror complete? Exiting ..."
	  exit 0

   else

      T1=`du -sk $DIR|gawk '{print $1}'`
      sleep $WDELAY
      T2=`du -sk $DIR|gawk '{print $1}'`
      T=$(($T2-$T1))

      if [ "$T" != "0" ]; then

	     echo
         echo "Rsync wrote $T k in the last $WDELAY;  monitoring status OK."
	     echo

      else

         echo
         echo "Rsync connection dead, killing rsync ..."
         killall -9 $1 rsync &> /dev/null
         echo
         echo "Waiting $RDELAY for interfaces to reconnect ... "
         sleep $RDELAY
         echo
         echo "Restarting rsync by spawning: $1"
		 echo "And waiting, $IDELAY, before restarting monitoring."
		 echo
         $1 &
		 sleep $IDELAY
		 echo
		 echo "Starting monitor."
		 echo

      fi

   fi
   
done

exit 0
