#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/inotify.h>
#include <errno.h>

#define BUF_SIZE	16384

struct events {
  int event;
  char *desc;
} events[] = {
  {IN_OPEN, 		"File was opened."},
  {IN_ACCESS,		"File was accessed (read)"},
  {IN_ATTRIB,		"Metadata  changed"},
  {IN_CREATE,		"File/directory created in watched directory."},
  {IN_DELETE,		"File/directory deleted from watched directory."},
  {IN_DELETE_SELF,	"Watched file/directory was itself deleted."},
  {IN_MODIFY, 		"File was modified."},
  {IN_MOVE_SELF, 	"Watched file/directory was itself moved."},
  {IN_MOVED_FROM, 	"Generated for the directory containing the old filename when a file is  renamed."},
  {IN_MOVED_TO, 	"Generated  for the directory containing the new filename when a file is renamed"},
  {IN_CLOSE_WRITE, 	"File opened for writing was closed."},
  {IN_CLOSE_NOWRITE, 	"File not opened for writing was closed."},
  {0, NULL}
};

int main(int argc, char *argv[])
{
  char buf[BUF_SIZE];
  struct inotify_event *iev;
  int inw, idx, i, r, counter = 0;
  
  if (argc < 2) {
    fprintf(stderr,"Usage: %s <path>\n", argv[0]);
    exit(1);
  }
  
  if ((inw = inotify_init()) < 0) {
    perror("inotify_init()");
    exit(1);
  }
  if (inotify_add_watch(inw, argv[1], IN_ALL_EVENTS) < 0) {
    perror("inotify_add_watch");
    exit(1);
  }
  while(1) {
    r = read(inw, buf, BUF_SIZE);
    if (r < 0) break;
    for(idx=0; idx < r; idx += (sizeof(struct inotify_event) + iev->len)) {
      iev = (struct inotify_event *)(buf+idx);
      for(int i=0; events[i].event; i++)
	if ((events[i].event & iev->mask) == events[i].event)
	  printf("%s (%s)\n", events[i].desc, iev->name);
    }
  }
}
