#!/bin/bash
#/usr/local/sbin/esamesync-esame.sh

# Host for the sync operation
# (A different value can be specified in /etc/sysconfig/esamesync-esame)
ESAMESYNCHOST=master3.edu-al.unipmn.it

# Max delay in case of errors (a random delay will be used, calculated
# between 0 and this value).
# (A different value can be specified in /etc/sysconfig/esamesync-esame)
MAXSLEEP=30

# Sysadmin can override local vars here:
CONFFILE=/etc/sysconfig/esamesync-esame


# Load configuration override if present:
if [ -e CONFFILE ]; then
    . ${CONFFILE}
fi

/usr/local/bin/bta-netwait ${ESAMESYNCHOST}

/bin/cat <<MSG
Starting /opt/esame syncronization (if it seems to be stuck, please wait for
a few minutes for your updates to take place; they can require a long time)

        DON'T TURN OFF THIS MACHINE NOW, JUST WAIT UNTIL FINISHED

MSG

DST=/opt/esame/
SRC=rsync://${ESAMESYNCHOST}/opt/esame/

# At boot the DST directory may not be immediately available.
# In case of errors, just wait a bit and try again later.
# (TBH, I only had this problem when the permission on /opt
#  were wrongly set to 770 instead of 775).
while ! cd ${DST} ; do
      SLEEPTIME="$(expr $RANDOM % $MAXSLEEP)"
      echo "Error entering ${DST}, sleeping for ${SLEEPTIME} seconds."
      sleep ${SLEEPTIME}
done

# To fix spurious errors, we pause and repeat the sync if necessary.
# Note: excluding /opt/google as that is installed locally with RPMs.
# Note: excluding /opt/esame as it is already syncronized on every boot.
#
while ! rsync -avq --sparse --progress --delete --whole-file ${SRC} . ; do
      SLEEPTIME="$(expr $RANDOM % $MAXSLEEP)"
      echo "Error from rsync, sleeping for ${SLEEPTIME} seconds."
      sleep ${SLEEPTIME}
done
