#!/bin/sh

T="$(date +%s%N)"

if [ "$(rpm -qa createrepo)" == "" ] ; then
	yum install createrepo -q -y
fi

yum clean all

CURRPATH=${PWD}
cd ${CURRPATH}

CURRBASENAME=${CURRPATH##*/}

if [ "${CURRBASENAME}" != "epel" ] ; then
	echo
	echo "* Your current path is '${CURRPATH}'"
	echo "  - Need path as '/home/rpms/<domain>/repo/epel'"
	echo "    where 'rpms' as client in Kloxo-MR 7.0"
	echo
	exit
fi

if [ "$(yum list *yum*|grep '@')" == "" ] ; then
	OPTIONS=""
else
	OPTIONS="--no-database --checksum=sha"
fi

chmod -R o-w+r ${CURRPATH}

echo "*** Delete old repodata dirs..."
find ${CURRPATH}/ -type d -name "repodata" -exec rm -rf {} \; >/dev/null 2>&1

cd ${CURRPATH}

for type in archive ; do
	for ver in 5 ; do
		for item in i386 x86_64 SRPMS ; do
			if [ ! -d ${CURRPATH}/${type}/epel/${ver}/${item} ] ; then
				mkdir -p ${CURRPATH}/${type}/epel/${ver}/${item}
			fi

			echo "*** Download for '${type}-epel-${ver}-${item}'..."
			cd ${CURRPATH}/${type}/epel/${ver}/${item}
			wget -r -l 1 -N -nd -R "index.html" http://archives.fedoraproject.org/pub/${type}/epel/${ver}/${item}
			find ./ -type f ! -name "*.rpm" -exec rm -rf {} \; >/dev/null 2>&1

			echo "*** Process for '${type}-epel-${ver}-${item}'..."
			createrepo ${OPTIONS} ${CURRPATH}/${type}/epel/${ver}/${item}
		done
	done
done

find ${CURRPATH}/ -type d -name ".repodata" -exec rm -rf {} \; >/dev/null 2>&1

cd ${CURRPATH}

sh /script/fix-chownchmod --client=rpms

# Time interval in nanoseconds
T="$(($(date +%s%N)-T))"
# Seconds
S="$((T/1000000000))"
# Milliseconds
M="$((T/1000000))"

echo ""
printf "*** Process Time: %02d:%02d:%02d:%02d.%03d (dd:hh:mm:ss:xxxxxx) ***\n" \
	"$((S/86400))" "$((S/3600%24))" "$((S/60%60))" "$((S%60))" "${M}"
echo ""

