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

static void
stuff_changed (GFileMonitor *monitor,
		   GFile *file,
		   GFile *other_file,
		   GFileMonitorEvent event_type,
		   gpointer user_data)
{
	char *name, *other;

	if (file)
		name = g_file_get_path (G_FILE (file));
	else
		name = g_strdup ("");

	if (other_file)
		other = g_file_get_path (G_FILE (other_file));
	else
		other = g_strdup ("");

	g_message ("%s: %s event %d (other %s)", __func__, name, event_type, other);
	g_free (name);
	g_free (other);
}

static GMainLoop *loop = NULL;

static void
signal_handler (int signo)
{
	if (signo == SIGINT || signo == SIGTERM) {
		g_message ("Caught signal %d, shutting down...", signo);
		g_main_loop_quit (loop);
	}
}

static void
setup_signals (void)
{
	struct sigaction action;
	sigset_t mask;

	sigemptyset (&mask);
	action.sa_handler = signal_handler;
	action.sa_mask = mask;
	action.sa_flags = 0;
	sigaction (SIGTERM,  &action, NULL);
	sigaction (SIGINT,  &action, NULL);
}

int main (int argc, char **argv)
{
	GFileMonitor *monitor;
	GFile *file;

	g_type_init ();

	if (argc != 2) {
		g_warning ("Bad arguments: need a file to watch");
		return 1;
	}

	file = g_file_new_for_path (argv[1]);
	monitor = g_file_monitor_file (file, G_FILE_MONITOR_NONE, NULL, NULL);
	g_signal_connect (monitor, "changed", G_CALLBACK (stuff_changed), NULL);

	loop = g_main_loop_new (NULL, FALSE);
	setup_signals ();
	g_main_loop_run (loop);

	g_object_unref (file);
	return 0;
}

