#!/bin/sh

REPORT_MAIL=false
REPORT_FILE=$(mktemp aptitude-run-mailreport.XXXXXXXXXX)
REPORT_RCPT=root

REPORTING_HELPERS="$(dirname $0)/reporting-helpers"
if [ -f "$REPORTING_HELPERS" ]; then
    . "$REPORTING_HELPERS"
else
    echo "E: $REPORTING_HELPERS helpers not present, bailing out." 1>&2
    exit 1;
fi

if [ -z "$REPORT_FILE" ]; then
    echo "ERROR: $0: Couldn't create temporary file in `pwd` using mktemp. Aborting." | \
        mail -s "aptitude-robot report on $(hostname) (ERROR)" $REPORT_RCPT
    exit 1
fi

cat >> $REPORT_FILE << EOF
Aptitude-Robot Report
=====================
EOF

#
# check for remaining upgrades
#
REMAINING_UPGRADES="$(remaining_upgrades)"
if [ -n "$REMAINING_UPGRADES" ]; then
    COLOR=red
    MSG="${MSG}${REMAINING_UPGRADES}"
fi

#
# check for errors in log file
#
ERRORS_IN_LOGFILE=$(errors_in_logfile "$1")
if [ "$ERRORS_IN_LOGFILE" = "errors" ]; then
        REPORT_MAIL=true
        cat >> "$REPORT_FILE" << EOF

Log File Errors
---------------
Please investigate the errors mentioned in the log file

EOF
        print_logfile "$1" >> "$REPORT_FILE"
elif [ "$ERRORS_IN_LOGFILE" = "notfound" ]; then
    REPORT_MAIL=true
    cat >> "$REPORT_FILE" << EOF

Missing Log File
----------------
aptitude-robot produced no log file.  Please investigate.
EOF
fi

if [ "$REPORT_MAIL" = true ]; then
    mail -s "aptitude-robot report on $(hostname)" "$REPORT_RCPT" < "$REPORT_FILE"
fi
rm "$REPORT_FILE"
