#!/bin/sh

. autorepo-config
. autorepo-sh-functions

autorepo_lock_workdir_or_exit

autorepo-try-rebuild-unmets
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
autorepo-purge -q --list > "$PURGE_TODO"
# some of them are unpurgeable
[ -s "$PURGE_TODO" ] && autorepo-mail-mainrepo-older

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/unmets.diff."* ; do
    if [ -s "$logfile" ]; then
	error_found=1
    else
	rm -f "$logfile"
    fi
done
if [ -n "$error_found" ]; then
    send_problems_mail "$PURGE_TODO" "$AUTOREPO_HOME/unmets.diff."*
fi

autorepo_unlock_workdir_safe
