#!/bin/sh
#
#   ubucdimage - provides an easy way to sync daily ISO files from an
#                Ubuntu CD image mirror.
#
#   Copyright (C) 2006 - 2009 Nafallo Bjälevik
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

set -e

if [ ! -f /etc/ubumirror.conf ]; then
    echo "Configuration file /etc/ubumirror.conf not found."
    exit 2
fi

. /etc/ubumirror.conf

LOGFILE="$LOGDIR/ubucdimage.log"

# Log all activity to file.
exec >> $LOGFILE 2>&1

if [ -z "$UBUCDI_DIR" ]; then
    echo -n "No Ubuntu cdimage target directory (UBUCDI_DIR) set in "
    echo "/etc/ubumirror.conf."
    exit 2
fi

LOCK="${UBUCDI_DIR}/Archive-Update-in-Progress-${HOSTNAME}"

trap 'rm -f $LOCK > /dev/null 2>&1; savelog -c 28 -n $LOGFILE > /dev/null' EXIT

# Get in the right directory and set the umask to be group writable
cd $HOME
umask 022

echo "$(date -R): Initiating Ubuntu daily CD image mirror operations..."

# Check to see if another sync is in progress
if ! ( set -o noclobber; echo "$$" > "${LOCK}") 2> /dev/null; then
        if ! $(kill -0 $(cat ${LOCK}) 2>/dev/null); then
                # Process does either not exist or is not owned by us.
                echo "$$" > "${LOCK}"
        else
                echo "$(date -R): Unable to proceed with operations; lock file still exists for PID $(cat ${LOCK})."
                exit 1
        fi
fi

echo "$(date -R): Lock established for process $(cat $LOCK)."

set +e

echo "$(date -R): Initiating cdimage sync..."

mkdir -p $UBUCDI_DIR

rsync -av --partial \
    --timeout=$IO_TIMEOUT \
    --bwlimit=$SPEED \
    --exclude ".trace/${HOSTNAME}" \
    $UBUCDI_EXCLUDE \
    $UBUCDI_MIRROR $UBUCDI_DIR

if [ $? -ne 0 ]; then
    ( echo "CDimage sync failed. Please check logs."; \
        egrep '^write failed|@ERROR' $LOGFILE ) | mail -s "Ubuntu cdimage sync failed" $EMAIL
    echo "$(date -R): sync for cdimage failed."
    exit 2
fi

echo "$(date -R): sync for cdimage completed."

echo "$(date -R): Releasing lock file..."
rm -f $LOCK > /dev/null 2>&1

echo "$(date -R): Ubuntu daily CD image mirror operations completed."
