#!/bin/bash
#
# OnApp (www.onapp.com)
#
# Cron script to synck FreeBSD bootable iso image: boot-freebsd-onapp.iso
# by Yura Kohut (ykohut@onapp.com)
#
## Changelog ##
# * Tue Sep 10 2013 - Add checking whether ISOs exist before sync
# * Wed May 18 2011 - initial creation

CONNECT_TIMEOUT=300
RANDOMIZE=600
FREEBSD_ISO_PATH=/onapp/tools/freebsd/
USE_SLEEP=1
usage()
{
      echo >&2 "Usage: $0 [-p ISO_PATH] [-s MAX_SLEEP] [ -t CONNECT_TIMEOUT] [-n] [-h]
                           -p ISO_PATH        : the local path where the ISOs are stored
                                                the default is /onapp/tools/freebsd/

                           -s MAX_SLEEP       : maximum amount of seconds (the exact value is determined randomly) to sleep before sync
                                                the default is 600 seconds

                           -t CONNECT_TIMEOUT : rsync ConnectTimeout in seconds
                                                the default is 300 seconds

                           -n : do not 'sleep', start sync immediately 
                           -h : print this info
"
}

while getopts p:s:t:nh o
do      case "$o" in
          p)      FREEBSD_ISO_PATH="$OPTARG";;
          s)      RANDOMIZE="$OPTARG";;
          t)      CONNECT_TIMEOUT="$OPTARG";;
          h)      usage; exit 0;;
          n)      USE_SLEEP=0;;
        esac
done

if [ -f /onapp/onapp-hv-install/onapp-hv-install.conf ]; then
    source /onapp/onapp-hv-install/onapp-hv-install.conf
    if [ "x${FREEBSD_ISOS}" != "x" ]; then
          FREEBSD_ISO=`echo ${FREEBSD_ISOS} 2>/dev/null | sed 's/FreeBSD\///g' 2>/dev/null`
    fi
fi

if [ "x${FREEBSD_ISO}" = "x" ]; then
    FREEBSD_ISO="boot-freebsd-onapp.iso boot-freebsd-onapp-generic.iso boot-freebsd-onapp-3.3.iso"
fi
source /etc/onapp.conf

[ ! -e $FREEBSD_ISO_PATH ] && mkdir -p $FREEBSD_ISO_PATH

if [ "x${FILE_TRANSFER_SERVER}" = "x" ]; then
    echo "File Transfer Server isn't configured.
Please run: # /onapp/onapp-hv-install/onapp-hv-config.sh -f <FTS_IP>
    where: FTS_IP - File Transfer Server FQDN or IP address from which ISOs are synced"
    exit 1
fi

if [ $USE_SLEEP -eq 1 ]; then 
    SLEEP=$((RANDOM%$RANDOMIZE+0))
    echo "Sync '$FREEBSD_ISO' in $SLEEP seconds from $FILE_TRANSFER_SERVER:/data/..."
    sleep $SLEEP
else
    echo "Sync '$FREEBSD_ISO' from $FILE_TRANSFER_SERVER:/data/ immediately"
fi
for ISO in ${FREEBSD_ISO}; do
    echo "Sync $ISO..."
    rsync -r -e "ssh -o ConnectTimeout=${CONNECT_TIMEOUT}" root@$FILE_TRANSFER_SERVER:/data/${ISO} $FREEBSD_ISO_PATH
done
