#!/bin/sh -eu
# osec.cron
#
# This file is part of Osec (lightweight integrity checker)
# Copyright (c) 2002-2007 by Stanislav Ievlev
# Copyright (c) 2008-2009 by Alexey Gladkov
#
# This file is covered by the GNU General Public License,
# which should be included with osec as the file COPYING.
#

PROG="${0##*/}"
NICE_ARGS=
IONICE_ARGS='-t'

. /etc/osec/pipe.conf

syslog()
{
	local log
	if log="$(which logger 2>/dev/null)"; then
		SHREQ=0 "$log" -p user.info -t "osec[$$]" "$*" ||:
	fi
}

TEMPFILE=
exit_handler()
{
	local rc=$?
	trap - EXIT
	[ -z "$TEMPFILE" ] ||
		rm -rf -- "$TEMPFILE"
	[ "$rc" = 0 ] ||
		syslog "Aborted rc=$rc"
        exit $rc
}

cmd=
run_osec()
{
	local rc=0
	$cmd /usr/bin/osec -D /var/lib/osec -f /etc/osec/dirs.conf ||
		rc=$?
	if [ $rc -ne 0 ]; then
		echo "Program exited abnormally, exit code = $rc" >&2
		syslog "/usr/bin/osec exited abnormally, exit code = $rc"
	fi
}

if [ -n "${NICE_PRIORITY-}" ] && nice_cmd="$(which nice 2>/dev/null)"; then
	$nice_cmd -n "$NICE_PRIORITY" true 2>/dev/null &&
		cmd="$nice_cmd $NICE_ARGS -n $NICE_PRIORITY --"
fi

if [ -n "${IONICE_PRIORITY-}" ] && ionice_cmd="$(which ionice 2>/dev/null)"; then
	$ionice_cmd -t -c $IONICE_PRIORITY true 2>/dev/null &&
		cmd="$cmd $ionice_cmd $IONICE_ARGS -c $IONICE_PRIORITY --"
fi

trap exit_handler HUP PIPE INT QUIT TERM EXIT
TEMPFILE="$(mktemp -t "$PROG.XXXXXX")"

syslog "Started"

if [ ! -d /var/lib/osec/.dbver1 ]; then
	syslog "Migration to new database format started"
	for db in /var/lib/osec/osec.cdb.*; do
		[ "$db" != '/var/lib/osec/osec.cdb.*' ] ||
			break
		$cmd /usr/bin/osec-migrade-db -D /var/lib/osec "$db"
	done
	mkdir /var/lib/osec/.dbver1
	syslog "Migration finished"
fi

run_osec |eval "$REPORT_PIPE" >"$TEMPFILE"

ADDED=0 REMOVED=0 CHANGED=0
while read l; do
	case "$l" in
		'No changes')
			[ -z "${IGNORE_NO_CHANGES-}" ] ||
				exit 0
			;;
		'New files added to control:')	t='ADDED'	;;
		'Changed controlled files:')	t='CHANGED'	;;
		'Removed from control:')	t='REMOVED'	;;
		'- /'*) [ -z "${t-}" ] || eval "$t=\$((\$t+1))"	;;
	esac
done < "$TEMPFILE"

STAT="chg=$CHANGED,add=$ADDED,del=$REMOVED"
export ADDED REMOVED CHANGED STAT

cat "$TEMPFILE" |eval "$SEND_PIPE"

syslog "Finished"
