#!/usr/bin/bash

DAYS=14
RESULTDIR=$(awk -F "=" '/^destdir/ {print $2}' /etc/copr/copr-be.conf)

if [ ! -d $RESULTDIR ]; then
   echo "ERROR: destdir ($RESULTDIR) in /etc/copr/copr-be.conf does not exist."
   exit 1
fi

pushd $RESULTDIR >/dev/null
for REPO in $( ls -d */*/* | grep -v '/repodata$' ); do
    pushd $REPO >/dev/null

    # Removing failed builds
    for FAILED in $(find -name 'fail' -mtime +$DAYS); do
        rm -rf $(dirname $FAILED)
        echo -n .
    done

    # Query latest (sucessfull) packages
    LATEST_PKGS=$(mktemp)
    ERR_LOG=$(mktemp)
    # "yum clean metadata" does not work on this custom repos
    rm -rf $(find /var/tmp -name query)
    rm -rf /var/tmp/createrepo*
    rm -rf /var/cache/yum/*
    repoquery --repofrompath=query,$RESULTDIR/$REPO --repoid=query -a --location 2>$ERR_LOG \
        | cut -c8- > $LATEST_PKGS
    # remove directory if it does not have repodata at all
    grep 'Cannot retrieve repository metadata' $ERR_LOG && rm -rf $RESULTDIR/$REPO

    # Remove builds older then $DAYS days and which have newer builds available
    for SUCCESS in $(find -name success -mtime +$DAYS); do
        DIR=$(basename $(dirname $SUCCESS))
        for PACKAGE in $(ls $DIR); do
            grep $PACKAGE $LATEST_PKGS >/dev/null && continue 2
        done
        # package was not found in $LATEST_PKGS
        rm -rf $DIR
        echo -n .
    done

    rm -f $LATEST_PKGS $ERR_LOG
    # unless we previosly deleted the repo, regen metadata
    if [ -d $(pwd) ]; then
        runuser -c "createrepo_c --update -q --ignore-lock $(pwd)" - copr &>/dev/null || runuser -c "createrepo_c --update -q --ignore-lock $(pwd)" - copr
    fi
    popd >/dev/null
done
popd >/dev/null
rm -rf /var/tmp/createrepo*
echo
echo Done
