#!/bin/bash -efu

. inotifier-functions.sh

msg_str="$(cat "$TTY_MESSAGE_FILE" 2>/dev/null)"
if [ -z "$msg_str" ]; then
    echo "Using the default user message" >&2
    msg_str='You have attempted to run a damaged file: %s (%s)\n'
fi

# @400000005cc2f40c1733bc44 Mar 15 23:30:58 comp-core-i5-4570-490e11.localdomain audit[1442]: INTEGRITY_DATA pid=1442 uid=0 auid=0 ses=1 subj=generic_u:generic_r:generic_t:s0 op="appraise_data" cause="IMA-signature-required" comm="notifier.sh" name="/etc/integrity/real_notify.sh" dev="sda2" ino=420510 res=0

#shellcheck disable=SC2034
tail -qF "$LOGDIR/current" | \
    while read -r ts f1 f2 f3 f4 f5 f6 _pid _uid f9 ses subj op cause comm rest; do
        check_timestamp "$ts" || continue
	uid="${_uid#*=}"
	check_uid "$uid" || continue
        username="$(id -n -u "$uid" 2>/dev/null)" || continue
	#shellcheck disable=SC2059
        printf "$msg_str" "${comm#*=}" "${cause#*=}" | \
            notify_tty_user "$username" ||:

        if [ -s "$NOTIFY_ALSO_FILE" -a -s "$NOTIFY_ALSO_FILE" ]; then
            grep -v '^#' "$NOTIFY_ALSO_FILE" | while read -r also_uid; do
		also_username="$(id -n -u "$also_uid" 2>/dev/null)" || continue
		[ "$also_username" != "$username" ] || continue
                echo "$f1 $f2 $f3 $f4 $f5 $f6 $_pid $_uid $f9 $ses $subj $op $cause $comm $rest" | notify_tty_user "$also_username" ||:
            done
        fi
    done
