#!/bin/bash

#---------------------------------------------------------------
# @reboot [part to shell script]filemon.sh
#
# MDIR: Directory to monitor
# LDIR: Directory to keep logs
#

DIR="/home/auser/Desktop/inotify/";
MDIR="${DIR}area/";
LDIR="${DIR}storage/";
path_exclude_list="${DIR}bin/exclude_list.txt";
#

echo "monitoring" $MDIR
echo "logging to" $LDIR

#--------------------------------------------------------
# stat --printf="Format"
#--------------------------------------------------------
# %n	file name
# %s	total size, in bytes
# %w	time of file birth, human-readable; - if unknown
# %y	time of last data modification, human-readable
#--------------------------------------------------------
file_modified() {
	fname=$2;
	path=$1$2;
	last_modified=$(date -r "$path" "+%Y%m%d-%H%M%S");
	file_stat=$(stat "$path" --printf="File=%n\nSize=%s\nModify=%y\nBirth=%w");
	echo "$last_modified $path";
	FN_HEAD="mdf-$last_modified-[h]-$fname";
	FN_BODY="mdf-$last_modified-[b]-$fname";
	cat "$path";
	echo "$file_stat" > "$LDIR$FN_HEAD";
	cat "$path" > "$LDIR$FN_BODY";
}

<<mycomment
file_removed() {
	cat "$1$2"
}

file_created() {
	TIMESTAMP=`date`
	echo "[$TIMESTAMP]: The file $1$2 was created"
}
mycomment

#
# inotifywait -q -m -r -e modify,delete,create $MDIR
#
# inotifywait's output format is 'DIRECTORY EVENT FILE'
#
# (e.g)
# test/hello/ MODIFY test.txt
# test/hello/ CREATE,ISDIR jjj
# test/hello/jjj/ CREATE test2.txt
# test/hello/jjj/ MODIFY test2.txt
#
inotifywait -m -r -e modify --fromfile "$path_exclude_list" $MDIR | while read DIRECTORY EVENT FILE; do
	case $EVENT in
	 MODIFY*)
	 	file_modified "$DIRECTORY" "$FILE"
	 	;;
	# CREATE*)
	# 	file_created "$DIRECTORY" "$FILE"
	# 	;;
	# DELETE*)
	# 	file_removed "$DIRECTORY" "$FILE"
	# 	;;
	esac
done

read -p "Press any key to resume ..."
