#!/bin/bash

RSYNC="/usr/bin/rsync"
OPTS="--quiet --recursive --links --perms --times --devices --specials --delete --timeout=300"                                      
DST="/opt/gentoo-rsync"
SYNCFILE="${DST}/last_sync"
SERVDIR="${DST}/portage"

NOW=$(date +%s)
if [[ ! -f ${SYNCFILE} ]];
then
        echo ${NOW} > ${SYNCFILE}
fi
LAST_SYNC=$(cat ${SYNCFILE})

# Set up the sync environment
if [[ ( ! -h ${SERVDIR} ) && ( -d ${SERVDIR} ) ]];
then
        mv ${SERVDIR} ${SERVDIR}.0
        ln -snf $SERVDIR.0 ${SERVDIR}
fi
mkdir -p ${SERVDIR}.0 ${SERVDIR}.1

if [[ ! -h ${SERVDIR} ]];
then
        ln -snf ${SERVDIR}.0 ${SERVDIR}
fi

# check where the current link points to and extract the number at the end                                                          
CURNUM=$(stat -c %N ${SERVDIR} | awk '{ print $3 }' | xargs echo | awk -F. '{{ print $NF }}')                                       
NEXTNUM=$(( (${CURNUM}+1)%2 ))
NEXTDIR="${SERVDIR}.${NEXTNUM}"

echo "Started update at" `date` >> $0.log 2>&1
logger -t rsync "Syncing local tree"
/usr/bin/eix-sync -q >> $0.log 2>&1
if [[ $? -ne 0 ]];
then
        # Retry once
        echo "First sync failed, retrying... " `date` >> $0.log 2>&1                                                                
        /usr/bin/eix-sync -q >> $0.log 2>&1
        if [[ $? -ne 0 ]];
        then
                # Only print warning if last sync is over 24 hours ago                                                              
                if [[ $(( ${NOW}-${LAST_SYNC} -gt 60*60*24 )) ]];
                then
                        echo "Failed to sync from master server"
                fi
                echo "Second sync failed too, giving up... " `date` >> $0.log 2>&1                                                  
                exit 1
        fi
fi
echo ${NOW} > ${SYNCFILE}

logger -t rsync "Syncing to ${NEXTDIR}"
${RSYNC} ${OPTS} --exclude=/distfiles /usr/portage/ ${NEXTDIR}/ >> $0.log 2>&1                                                      
logger -t rsync "deleting spurious Changelog files"
find ${NEXTDIR} -iname ".ChangeLog*" | xargs rm -rf
logger -t rsync "Switching to ${NEXTDIR} as active repository"
ln -snf ${NEXTDIR} ${SERVDIR}

echo "End: "`date` >> $0.log 2>&1

