#!/bin/bash

LOG_DIR="/tmp/fly-msg"
LOG_FILE="$LOG_DIR/msg.txt"
NAME=`basename $0`
LOCK_FILE="/tmp/$NAME-${DISPLAY}.lock"
CONF_FILE="/etc/digsig/digsig_initramfs.conf"
if [ $LANG = "ru_RU.UTF-8" ]; then
MESSAGE="Внимание, cообщение!"
else
MESSAGE="Attention, message!"
fi

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

function wait_for_file() {
#check log file and wait for it
if [ ! -f $LOG_FILE ]; then
    while true ; do
        if [ ! -d $LOG_DIR ]; then mkdir -m 777 $LOG_DIR; fi

        inotifywait -qq -r -e create $LOG_DIR &
        wait $!

        #file arrived, delay to get already not empty file
        sleep 1
        if [ -f $LOG_FILE ]; then break; else sleep 2; fi
    done
fi
}

trap terminate INT TERM HUP KILL

#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

#if required then create dir and wait file in it
wait_for_file

#wait changes in log file
while true ; do
    if [ -s $LOG_FILE ]; then
      MSG="empty"
      MSG=$(tail -10 $LOG_FILE)
      echo "$MSG" > ~/txt.txt
#     notify-send -u critical -t 10000 -i dialog-warning "$MESSAGE" "$MSG"
#     fly-dialog --caption "$MESSAGE" --msgbox "$MSG"
      fly-dialog --caption "$MESSAGE" --textbox ~/txt.txt
      rm ~/txt.txt
    fi

    #wait for changes
    inotifywait -qq -r -e modify $LOG_FILE &
    wait $!

    #if dir or file are deleted then wait for it again
    if [ ! -f $LOG_FILE ]; then
      wait_for_file
      #restart
      pkill inotifywait
    fi
done

terminate
