#!/bin/bash

if [ $# -ne 2 ]; then
	echo "Exactly two parameter needed. category and /path/to/logfile"
	exit 1
fi

exec >> $2
exec 2>&1

CURDATE=`date +%s`
LAST_SYNC_ARG=""

if [ "${1}" ==  "Linux" ]; then
	LAST_SYNC_ARG="-f -r"
	CATEGORY="${1}"
elif [ "${1}" ==  "EPEL" ]; then
	LAST_SYNC_ARG="-e"
	CATEGORY="${1}"
elif [ "${1}" ==  "Secondary" ]; then
	LAST_SYNC_ARG="-s"
	CATEGORY="Secondary Arches"
fi

if [ "${LAST_SYNC_ARG}" == "" ]; then
	echo "Category is either Linux or EPEL"
	exit 1
fi

if [ -e /var/run/mirrormanager/umdl-${1} ]; then
	. /var/run/mirrormanager/umdl-${1}
else
	# 48 hours -> 172800 seconds
	let LASTRUN=CURDATE-172800
fi

let DELTA=CURDATE-LASTRUN

/usr/local/bin/last-sync -d ${DELTA} -q ${LAST_SYNC_ARG}

if [ "$?" -ne "0" ]; then
	# no changes on the master mirror
	# abort
	exit 0
fi

echo -n "Last sync more than ${DELTA} seconds ago. Running umdl for Fedora ${CATEGORY} at "
date

/usr/local/bin/lock-wrapper umdl-${1} "/usr/bin/mm2_update-master-directory-list --category \"Fedora ${CATEGORY}\""

if [ "$?" -eq "0" ]; then
	# success! remember the date of this run
	echo "LASTRUN=${CURDATE}" > /var/run/mirrormanager/umdl-${1}
	echo -n "Finished umdl for Fedora ${CATEGORY} successfully at "
	date
	exit 0
fi

echo -n "umdl for Fedora ${CATEGORY} returned non-zero. Something failed. Please check umdl.log. "
date
