#!/bin/bash

LOCKFILE=/var/cache/fedoracommunity/fedora-packages-yum.lock

rebuild=$(cat <<"EOF"
echo 'Trying makecache.'
/usr/bin/yum makecache -c /etc/fedoracommunity/yum-repo.conf --enablerepo=*
echo 'Releasing $LOCKFILE'
EOF
)
nuke_and_rebuild=$(cat <<"EOF"
echo 'Nuking.'
rm /var/cache/fedoracommunity/packages/tmp/var/lib/rpm/__db.*
/usr/bin/rpmdb --root=/var/cache/fedoracommunity/packages/tmp/var/lib/rpm --rebuilddb
echo 'Trying makecache again now.'
/usr/bin/yum makecache -c /etc/fedoracommunity/yum-repo.conf --enablerepo=*
echo 'Releasing $LOCKFILE'
EOF
)


echo "Acquiring $LOCKFILE..."
flock $LOCKFILE -c "$rebuild"


# If it failed, then try to nuke and rebuild the rpmdb first.
if [ $? -eq 1 ] ; then
    echo 'makecache failed... sleeping for 10 seconds.'
    sleep 10
    echo 'Waking.  Now trying to rebuild the rpmdb.'

    echo "Acquiring $LOCKFILE..."
    flock $LOCKFILE -c "$nuke_and_rebuild"
fi
