#!/bin/bash

LOCKFILE=/var/run/sync-mirrors/lockfile
LOGFILE=/var/log/sync-mirrors/sync-mirrors-`date +%Y%m%d%H%M%S`.log
CONFDIR=/etc/sync-mirrors

usage() {
    echo "Usage: `basename $0` [-v] [mirror]" 1>&2
    echo "       `basename $0` -l" 1>&2
}

if [ -d ${CONFDIR} ]; then
    MIRRORLIST=`ls ${CONFDIR}/*.conf 2> /dev/null | while read f ; \
        do basename $f | sed -e 's/\.conf$//' ; done`
    if [ "${MIRRORLIST}" = "" ]; then
        echo "ERR: No configured mirrors found" 1>&2
        exit 1
    fi
else
    echo "ERR: Config directory [${CONFDIR}] missing" 1>&2
    exit 1
fi

VERBOSE=0
EXTRA_OPTS=""
while getopts "vhl" c ; do
    case $c in
	v)
	    VERBOSE=1
	    EXTRA_OPTS="-v --progress"
	    ;;
	h)
	    usage
	    exit 1
	    ;;
	l)
	    echo "Available mirrors:"
            for name in ${MIRRORLIST} ; do
		echo "  ${name}"
	    done
	    exit 0
	    ;;
    esac
done

shift `expr $OPTIND - 1`

if [ $# -gt 0 ]; then
    for mirror in $* ; do
        if [ ! -f ${CONFDIR}/$1.conf ]; then
            echo "ERR: No mirror named [$1]" 1>&2
            exit 1
        fi
        SYNC="${MIRRORS} $1"
        shift
    done
else
    SYNC=${MIRRORLIST}
fi

if [ `whoami` != mirror ]; then
    echo "ERR: Script needs to be run as mirror user" 1>&2
    exit 1
fi

umask 022

if [ -f ${LOCKFILE} ]; then
    kill -0 `cat ${LOCKFILE}`
    if [ $? -ne 1 ]; then
	which stat > /dev/null 2>&1
	if [ $? -eq 0 ]; then
	    STARTED=" (`stat ${LOCKFILE} | sed -n 's/^Modify: \(.*\)/\1/p'`)"
	else
	    STARTED=""
	fi
        echo "ERR: Lockfile exists${STARTED}, exiting" 1>&2
        exit 1
    else
        echo "WARN: Removing stale lock file..." 1>&2
        rm -f ${LOCKFILE}
    fi
fi
trap "rm -f ${LOCKFILE}" INT TERM EXIT
echo $$ > ${LOCKFILE}

for mirror in ${SYNC} ; do
    SRC=""
    RSYNCOPTS=""
    . ${CONFDIR}/${mirror}.conf
    if [ "${SRC}" = "" ]; then
        echo "ERR: No SRC set for mirror ${mirror} ..." 1>&2
        exit 1
    fi
    [ ${VERBOSE} -eq 1 ] && echo "Starting ${mirror} sync ..."
    echo "`date '+%Y/%m/%d %H:%M:%S'` [$$] Starting ${mirror} sync ..." \
        >> ${LOGFILE}
    rsync -aH -4 ${EXTRA_OPTS} --numeric-ids --delete --delete-after \
        --delay-updates --no-motd ${RSYNCOPTS} --log-file=${LOGFILE} \
        ${SRC} /srv/mirrors/${mirror}/
done

rm -f ${LOCKFILE}
