#!/bin/sh

PATH=$HOME/bin:/bin:/usr/bin
export PATH

. autorepo-config
. autorepo-sh-functions

logfile=$AUTOREPO_HOME/autorepo-daily.log

send_failure_mail()
{
    attachedfile=$logfile
    local adate=$(date +"%Y%m%d")
    cat > $AUTOREPO_HOME/tmp.txt <<EOF
FAILED: autorepo $adate.
see attached log fle for details.
--
Sincerely yours, 
Autorepo service.
EOF
    mutt -x -s "FAILED: $GB_REPO_NAME $adate" -i $AUTOREPO_HOME/tmp.txt ${attachedfile:+-a "$attachedfile"} "$AUTOREPO_ADMIN_MAIL" </dev/null
    rm -f $AUTOREPO_HOME/tmp.txt
}

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

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


if ! autorepo-run > $logfile 2>&1; then
    send_failure_mail
fi

autorepo-cybertalk
autorepo-archive

error_found=
for logfile in "$AUTOREPO_HOME/unmets.diff."* ; do
    if [ -s "$logfile" ]; then
	error_found=1
    else
	rm -f "$logfile"
    fi
done
if [ -n "$error_found" ]; then
    send_unmets_mail "$AUTOREPO_HOME/unmets.diff."*
fi
