#!/bin/sh

PATH="/bin:/usr/bin"
LOGDIR="/var/log/aide"
LOGFILE="$LOGDIR/aide.log"
CONFFILE="/etc/aide/aide.conf"
ERRORLOG="$LOGDIR/error.log"

[ -f /usr/bin/aide ] || exit 0

MAILTO=`grep "^@@define MAILTO" $CONFFILE | head -1 | awk '{ print $3 }'`
DATABASE=`grep "^database=file:/" $CONFFILE | head -1 | cut -d: -f2`
LINES=`grep "^@@define LINES" $CONFFILE | head -1 | awk '{ print $3 }'`
FQDN=`hostname -f`
DATE=`date +"at %X on %x"`

[ -z "$MAILTO" ] && MAILTO="root"
[ -z "$DATABASE" ] && DATABASE="/var/lib/aide/aide.db"
[ -z "$LINES" ] && LINES="1000"


if [ ! -f $DATABASE ]; then
	(
	echo "Fatal error: The AIDE database does not exist!"
	echo "This may mean you haven't created it, or it may mean that someone has removed it."
	) | /usr/bin/mail -s "Daily AIDE report for $FQDN" $MAILTO
	exit 0
fi

[ -f $LOGFILE ] && savelog -t -g adm -m 640 -u root -c 7 $LOGFILE > /dev/null
[ -f $ERRORLOG ] && savelog -t -g adm -m 640 -u root -c 7 $ERRORLOG > /dev/null

aide --check >$LOGFILE 2>$ERRORLOG

(cat << EOF;
This is an automated report generated by the Advanced Intrusion Detection
Environment on $FQDN ${DATE}.

EOF
if [ -s $LOGFILE ]; then
	loglines=`wc -l $LOGFILE | awk '{ print $1 }'`
	if [ ${loglines:=0} -gt $LINES ]; then
		echo
		echo "TRUNCATED (!) output of the daily AIDE run:"
		echo "Output is $loglines lines, truncated to $LINES."
		head -$LINES $LOGFILE
		echo "The full output can be found in $LOGFILE."
	else
		echo "Output of the daily AIDE run:"
		cat $LOGFILE
	fi
else
	echo "AIDE detected no changes."
fi
if [ -s $ERRORLOG ]; then
	errorlines=`wc -l $ERRORLOG | awk '{ print $1 }'`
	if [ ${errorlines:=0} -gt $LINES ]; then
		echo "TRUNCATED (!) output of errors produced:"
		echo "Error output is $errorlines lines, truncated to $LINES."
		head -$LINES $ERRORLOG
		echo "The full output can be found in $ERRORLOG."
	else
		echo "Errors produced:"
		cat $ERRORLOG
	fi
else
	echo "AIDE produced no errors."
fi
) | /usr/bin/mail -s "Daily AIDE report for $FQDN" $MAILTO
