#!/bin/sh

. autorepo-config
. autorepo-sh-functions

autorepo_lock_workdir_or_exit

if [ -n "$AUTOREPO_MERGE_ROOT" ]; then
    cmd=$AUTOREPO_HOME/bin/autorepo-rsync-local
    [ -x $cmd ] && $cmd
    autorepo-merge-repositories
elif [ -z "$AUTOREPO_NO_REBUILD_UNMETS" ]; then
    autorepo-repo-unmets
    autorepo-try-rebuild-unmets
fi
autorepo-cybertalk
autorepo-archive
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
    autorepo-purge --purge $AUTOREPO_PURGE_ARGS
else
    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 [ -n "$AUTOREPO_MERGE_COMPONENTS" ] || [ -n "$AUTOREPO_PURGE_DESTPATH" ]; then
    autorepo-health-find-intersections > "$INTERSECTIONS_TODO"
fi
[ -s "$INTERSECTIONS_TODO" ] || rm -f "$INTERSECTIONS_TODO"

autorepo-check-health

AUTOREPO_TMP_MAIL_BODY=
cleanup_mail_trap() {
   [ -n "$AUTOREPO_TMP_MAIL_BODY" ] && rm -f "$AUTOREPO_TMP_MAIL_BODY"
   exit
}
trap cleanup_mail_trap INT TERM EXIT

send_problems_mail()
{
    local adate=$(date +"%Y%m%d")
    AUTOREPO_TMP_MAIL_BODY=`mktemp autorepo_mail.XXXXXXXXXX`
    echo "Problems detected: " >> "$AUTOREPO_TMP_MAIL_BODY"
    echo >> "$AUTOREPO_TMP_MAIL_BODY"
    autorepo_mail_cat_quoted_file "$AUTOREPO_TMP_MAIL_BODY" "$@"
    cat >> "$AUTOREPO_TMP_MAIL_BODY" <<EOF

--
Sincerely yours, 
Autorepo service.
EOF
    mutt -x -s "$GB_REPO_NAME: problems encountered at $adate" -i "$AUTOREPO_TMP_MAIL_BODY" -- "$AUTOREPO_ADMIN_MAIL" </dev/null
    rm -f "$AUTOREPO_TMP_MAIL_BODY"
}

error_found=
for logfile in "$PURGE_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_problems_mail \
	"$PURGE_TODO" \
	"$INTERSECTIONS_TODO" \
	"$AUTOREPO_HOME/unmets.diff."* \
	"$AUTOREPO_HOME/sourcerpm."*
fi

cmd=/usr/bin/autorepo-altnode-builder-statistics
[ -x $cmd ] && $cmd
autorepo_unlock_workdir_safe
