#!/bin/bash

LOG_DIR="/var/log"
LOG_FILE="/var/log/bins.log"
#LOG_FILE="/var/log/dmesg"
NAME=`basename $0`
LOCK_FILE="/tmp/$NAME-${DISPLAY}.lock"
CONF_FILE="/etc/digsig/digsig_initramfs.conf"

function terminate() {
	rm -f $LOCK_FILE
	pkill inotifywait
	exit 1
}

trap terminate INT TERM HUP KILL

#check digsig
if [ -f $CONF_FILE ]; then
  cat $CONF_FILE | grep -q "DIGSIG_ELF_MODE=0"
  if [ "$?" = 0 ]; then
    cat $CONF_FILE | grep -q "DIGSIG_XATTR_MODE=0"
    if [ "$?" = 0 ]; then
      echo "DIGSIG elf and xarttr modes inactive in $CONF_FILE"
      exit
    fi
  fi
else
  echo "DIGSIG inactive, no $CONF_FILE"
  exit
fi

#nothing to do
if [ ! -f /usr/bin/inotifywait ] ; then exit; fi

#lock
copy=`ps h -C $NAME | grep -v $$ | wc -l`

if [ $copy -gt 1 ] ; then
	[ -f $LOCK_FILE ] && exit
fi
echo $$ > $LOCK_FILE

#check log file and wait for it
if [ ! -f $LOG_FILE ]; then
    while true ; do
	inotifywait -qq -r -e create $LOG_DIR &
	wait $!
	if [ -f $LOG_FILE ]; then break; else sleep 2; fi
    done
fi

#wait changes in log file
while true ; do
    inotifywait -qq -r -e modify $LOG_FILE &
    wait $!
    MSG=""; TRAY_MSG=""
    MSG=$(tail -1 $LOG_FILE)
#alex: no pax since 1.6
#   echo "$MSG" | grep  -q PAX  && TRAY_MSG="Выполнение процесса заблокировано СЗ ОС (PaX): $MSG"
    echo "$MSG" | grep  -q DIGSIG && TRAY_MSG="Загрузка неподписанного файла заблокирована СЗ ОС (DIGSIG): $MSG"
    notify-send -t 1500 -i dialog-warning "$TRAY_MSG"
done

terminate
