#!/bin/sh
#
#   uburelease - provides an easy way to sync official ISO images from an
#                Ubuntu releases 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 "File /etc/ubumirror.conf does not exist!"
    exit 1
fi

. /etc/ubumirror.conf

LOGFILE="$LOGDIR/uburelease.log"

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

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

LOCK="${UBUREL_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 release 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 Ubuntu release CD image sync..."

rsync -av --partial --delete-after \
      --bwlimit=$SPEED \
      --timeout=$IO_TIMEOUT \
      --exclude ".trace/${HOSTNAME}" \
      --exclude Archive-Update-in-Progress-* \
      $UBUREL_EXCLUDE \
      $UBUREL_MIRROR $UBUREL_DIR

if [ $? -ne 0 ]; then
    ( echo "Ubuntu CD image sync failed. Please check logs."; \
        egrep '^write failed|@ERROR' $LOGFILE ) | mail -s "Ubuntu release sync failed" $EMAIL
    echo "$(date -R): Ubuntu releases CD images sync failed."
    exit 1
fi

echo "$(date -R): Ubuntu release CD image sync completed."

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

echo "$(date -R): Time-stamping trace file..."
date -u > "${UBUREL_DIR}/.trace/${HOSTNAME}"

echo "$(date -R): Ubuntu releases mirror operations completed."
