#!/bin/sh

. autorepo-config
. autorepo-lock-sh-functions
. autorepo-mail-sh-functions

autorepo_lock_workdir_or_exit

VERBOSE=
[ "$1" == "-v" ] && VERBOSE=1

[ -z "$VERBOSE" ] || echo "Running autorepo-repo-unmets ..."
autorepo-repo-unmets
if stat -t "$AUTOREPO_HOME/unmets.diff."* >/dev/null 2>&1
then
    # just do it again to be sure; sometimes we catch a bad Sisyphus state
    autorepo-repo-unmets
fi

PURGE_TODO="$AUTOREPO_HOME"/purge.TODO.txt
rm -f "$PURGE_TODO"
if [ "$AUTOREPO_PURGE_MODE" = 'auto' ]; then
    [ -z "$VERBOSE" ] || echo "Running autorepo-purge --purge $AUTOREPO_PURGE_ARGS > purge.log ..."
    autorepo-purge --purge $AUTOREPO_PURGE_ARGS > $AUTOREPO_HOME/purge.log
    if [ -s $AUTOREPO_HOME/purge.log ]; then
	cat $AUTOREPO_HOME/purge.log;
	autorepo-rebuild-repository
    else
	rm -f $AUTOREPO_HOME/purge.log;
    fi
else
    [ -z "$VERBOSE" ] || echo "Running autorepo-purge -q $AUTOREPO_PURGE_ARGS --list > $PURGE_TODO ..."
    autorepo-purge -q $AUTOREPO_PURGE_ARGS --list > "$PURGE_TODO"
    # some of them are unpurgeable
    [ -s "$PURGE_TODO" ] && autorepo-mail-mainrepo-older
fi

INTERSECTIONS_TODO="$AUTOREPO_HOME"/intersections.TODO.txt
rm -f "$INTERSECTIONS_TODO"
if [ -z "$AUTOREPO_AUTOPORTS_SUFFIX" ] && \
    ([ -n "$AUTOREPO_MERGE_COMPONENTS" ] || [ -n "$AUTOREPO_PURGE_DESTPATH" ]); then
    [ -z "$VERBOSE" ] || echo "Running autorepo-health-find-intersections > $INTERSECTIONS_TODO ..."
    autorepo-health-find-intersections > "$INTERSECTIONS_TODO"
fi
[ -s "$INTERSECTIONS_TODO" ] || rm -f "$INTERSECTIONS_TODO"

[ -z "$VERBOSE" ] || echo "Running autorepo-check-health ..."
autorepo-check-health

error_found=
for logfile in \
    "$PURGE_TODO" \
    "$INTERSECTIONS_TODO" \
    "$AUTOREPO_HOME/sourcerpm.missing" \
    "$AUTOREPO_HOME/sourcerpm.dangling" \
    "$AUTOREPO_HOME/sourcerpm.duplicate" \
    "$AUTOREPO_HOME/unmets.diff."* ; do
#    "$AUTOREPO_HOME/binaryrpm."*.missing \
#    "$AUTOREPO_HOME/binaryrpm."*.dangling \
    if [ -s "$logfile" ]; then
	error_found=1
    else
	rm -f "$logfile"
    fi
done
if [ -n "$error_found" ]; then
    send_mail_with_topic Problems \
	"$PURGE_TODO" \
	"$INTERSECTIONS_TODO" \
	"$AUTOREPO_HOME/unmets.diff."* \
	"$AUTOREPO_HOME/sourcerpm."*
fi

autorepo_unlock_workdir_safe
