#!/bin/sh

COLUMN=upd
COLOR=green

MSG="
Aptitude-Robot Report
=====================

"

# TODO: The following contains code very similar to
# mail-log-on-error. Should be factored out.

#
# check for remaining upgrades
#
UPGRADES_FILE=$(mktemp aptitude-upgrades.XXXXXXXXX)
if [ -z "$UPGRADES_FILE" ]; then
    COLOR=red
    MSG="${MSG}ERROR: $(basename $0): Can't check for remaining upgrades:
Couldn't create temporary file in `pwd` using mktemp.
"
else
    aptitude search '~U !~ahold' > "$UPGRADES_FILE"
    if [ -s "$UPGRADES_FILE" ]; then
        COLOR=red
        MSG="${MSG}
Remaining Upgrades:

$(cat "$UPGRADES_FILE")

"
    fi
    rm "$UPGRADES_FILE"
fi

#
# check for errors in log file
#
LOGFILE="$1"
if [ -f "$LOGFILE" ]; then
    if egrep -q -i '\bWarn|\bW:|^The following packages have unmet dependencies' "$LOGFILE" >/dev/null 2>/dev/null ; then
        COLOR=yellow
    fi
    if egrep -q -i '\bError\b|\bErr:|\bE:|^aptitude exited with value [^0]' "$LOGFILE"  >/dev/null 2>/dev/null; then
        COLOR=red
    fi

    MSG="${MSG}
$(cat "$LOGFILE")

"
else
    COLOR=red
    MSG="${MSG}

log file missing -- please investigate

"
fi

BB=/bin/false
if [ -x /usr/lib/hobbit/client/bin/bb ]; then
    BB=/usr/lib/hobbit/client/bin/bb
fi
if [ -x /usr/lib/xymon/client/bin/xymon ]; then
    BB=/usr/lib/xymon/client/bin/xymon
fi

if [ -f /etc/default/hobbit-client ]; then
    . /etc/default/hobbit-client
fi
if [ -f /etc/default/xymon-client ]; then
    . /etc/default/xymon-client
fi

for server in $HOBBITSERVERS $XYMONSERVERS; do
    $BB $server "@" << EOF
status+36h $CLIENTHOSTNAME.$COLUMN $COLOR $(date)

${MSG}
EOF
done

exit 0
