/*
 * gcc -o glib-test-monitor \
 *     `pkg-config --cflags --libs glib-2.0 gio-2.0` \
 *     glib-test-monitor.c
 */

#include <glib.h>
#include <gio/gio.h>
#include <time.h>

static const gchar *
monitor_event_to_string (GFileMonitorEvent event_type)
{
	switch (event_type) {
	case G_FILE_MONITOR_EVENT_CHANGED:
		return "G_FILE_MONITOR_EVENT_CHANGED";
	case G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT:
		return "G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT";
	case G_FILE_MONITOR_EVENT_DELETED:
		return "G_FILE_MONITOR_EVENT_DELETED";
	case G_FILE_MONITOR_EVENT_CREATED:
		return "G_FILE_MONITOR_EVENT_CREATED";
	case G_FILE_MONITOR_EVENT_ATTRIBUTE_CHANGED:
		return "G_FILE_MONITOR_EVENT_ATTRIBUTE_CHANGED";
	case G_FILE_MONITOR_EVENT_PRE_UNMOUNT:
		return "G_FILE_MONITOR_EVENT_PRE_UNMOUNT";
	case G_FILE_MONITOR_EVENT_UNMOUNTED:
		return "G_FILE_MONITOR_EVENT_UNMOUNTED";
	case G_FILE_MONITOR_EVENT_MOVED:
		return "G_FILE_MONITOR_EVENT_MOVED";
	}

	return "unknown";
}

static void
monitor_event_cb (GFileMonitor	    *file_monitor,
                  GFile	            *file,
                  GFile	            *other_file,
                  GFileMonitorEvent  event_type,
                  gpointer           user_data)
{
  gchar *uri;
  gchar *other_uri;

  uri = g_file_get_uri (file);
  other_uri = other_file ? g_file_get_uri (other_file) : NULL;

  if (event_type == G_FILE_MONITOR_EVENT_MOVED)
    {
      g_print ("%lu: Received '%s' event in '%s->%s'\n",
               time (NULL),
               monitor_event_to_string (event_type),
               uri,
               other_uri);
    }
  else
    {
      g_print ("%lu: Received '%s' event in '%s'\n",
               time (NULL),
               monitor_event_to_string (event_type),
               uri);
    }

  g_free (uri);
  g_free (other_uri);
}

int main (int argc, char **argv)
{
  GError *error = NULL;
  GFile *pathfile;
  GFileMonitor *monitor;

  g_type_init ();

  if (argc != 2)
    {
      g_printerr ("Usage: %s [--disable-virtual] DIRECTORY\n", argv[0]);
      return -1;
    }

  pathfile = g_file_new_for_commandline_arg (argv[1]);
  monitor = g_file_monitor_directory (pathfile,
                                      G_FILE_MONITOR_NONE,
                                      NULL,
                                      &error);
  if (!monitor)
    {
      g_printerr ("Couldn't monitor directory '%s': %s\n",
                  argv[1],
                  error ? error->message : "unknown error");
      g_clear_error (&error);
    }

  g_signal_connect (monitor,
                    "changed",
                    G_CALLBACK (monitor_event_cb),
                    NULL);

  while (1)
    {
      g_main_context_iteration (NULL, TRUE);
    }

  return 0;
}

