#include <libgnomevfs/gnome-vfs-ops.h>
#include <libgnomevfs/gnome-vfs-directory.h>
#include <libgnomevfs/gnome-vfs-utils.h>
#include <libgnomevfs/gnome-vfs-init.h>
#include <stdio.h>

static void
rb_library_watcher_monitor_cb (GnomeVFSMonitorHandle *handle,
			       const char *monitor_uri,
			       const char *info_uri,
			       GnomeVFSMonitorEventType event_type,
			       gpointer data)
{
}

static void
rb_library_watcher_add_directory (const char *dir)
{
	GnomeVFSMonitorHandle *handle = NULL;
	GList *list, *l;
	GnomeVFSURI *uri, *subdir_uri;
	char *tmp, *text_uri, *subdir_uri_text;

	if (dir == NULL)
		return;

	tmp = gnome_vfs_expand_initial_tilde (dir);
	uri = gnome_vfs_uri_new (tmp);
	g_free (tmp);
	if (uri == NULL || gnome_vfs_uri_exists (uri) == FALSE)
		return;

	text_uri = gnome_vfs_uri_to_string (uri, GNOME_VFS_URI_HIDE_NONE);

	gnome_vfs_directory_list_load (&list, text_uri,
				       (GNOME_VFS_FILE_INFO_GET_MIME_TYPE |
		  			GNOME_VFS_FILE_INFO_FORCE_FAST_MIME_TYPE |
					GNOME_VFS_FILE_INFO_FOLLOW_LINKS));

	for (l = list; l != NULL; l = g_list_next (l))
	{
		GnomeVFSFileInfo *info = l->data;

		if (info->type != GNOME_VFS_FILE_TYPE_REGULAR)
		{
		        /* recurse into directories, unless they start with ".", so we 
			   avoid hidden dirs, '.' and '..' */
		        if ((info->type == GNOME_VFS_FILE_TYPE_DIRECTORY) && 
			    (info->name) && (info->name[0] != '.'))
			{
			        subdir_uri = gnome_vfs_uri_append_path (uri, info->name);
				subdir_uri_text = gnome_vfs_uri_to_string
					(subdir_uri, GNOME_VFS_URI_HIDE_NONE);
				gnome_vfs_uri_unref (subdir_uri);
				rb_library_watcher_add_directory (subdir_uri_text);
				g_free (subdir_uri_text);
			}

			continue;
		}
	}

	gnome_vfs_file_info_list_free (list);

	fprintf (stderr, "Adding a VFS monitor for uri: %s\n", text_uri);
	gnome_vfs_monitor_add (&handle, text_uri, GNOME_VFS_MONITOR_DIRECTORY,
			       (GnomeVFSMonitorCallback) rb_library_watcher_monitor_cb, NULL);
	fprintf (stderr, "Added VFS monitor\n");

	g_assert (handle != NULL);

	g_free (text_uri);
}

int
main (int argc, char **argv)
{
	if (argc < 2)
	{
		fprintf (stderr, "Usage: %s directory\n", argv[0]);
		return 0;
	}

	gnome_vfs_init ();

	rb_library_watcher_add_directory (argv[1]);

	gnome_vfs_shutdown ();
	
	return 0;
}
