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

/* gcc -g $(pkg-config --cflags glib-2.0 gio-2.0) test.c $(pkg-config --libs glib-2.0 gio-2.0) */

void trash_changed (GFileMonitor *monitor,
        GFile *file,
        GFile *other_file,
        GFileMonitorEvent event_type,
        gpointer user_data)
{
    GMainLoop *loop = (GMainLoop *) user_data;
    char * uri = g_file_get_uri (file);

    switch (event_type)
    {
        case G_FILE_MONITOR_EVENT_CREATED:
            g_printf ("%s appeared - bug not reproduced :D\n", uri);

            g_file_delete (file, NULL, NULL);
            break;
        case G_FILE_MONITOR_EVENT_DELETED:
            g_printf ("Deleted - exiting.\n");
            g_main_loop_quit (loop);
            break;
    }
}

void monitor_trash (GMainLoop *loop)
{
    GFile *file;
    GFileMonitor *monitor;

    file = g_file_new_for_uri ("trash://");

    monitor = g_file_monitor_directory (file,
            G_FILE_MONITOR_NONE,
            NULL,
            NULL);

    g_object_unref (file);

    g_signal_connect (monitor,
            "changed",
            G_CALLBACK (trash_changed),
            loop);
}

void trash_test_file ()
{
    GFile *file = g_file_new_for_path ("test-file");

    g_object_unref (g_file_create (file,
                G_FILE_CREATE_NONE,
                NULL, /* GCancellable */
                NULL)); /* GError */

    if (!g_file_trash (file, NULL, NULL))
        g_error ("Couldn't trash file");
    else
        g_printf ("Trashed, now let's see if the bug is reproduced... ");

    g_object_unref (file);
}

void fail_quit (gpointer user_data)
{
    GMainLoop *loop = (GMainLoop *) user_data;

    g_printf("10 seconds later, we don't know that the file is in the trash. Bug :(\n");

    g_main_loop_quit (loop);
}

void main ()
{
    GMainLoop *loop;

    loop = g_main_loop_new (NULL, TRUE);

    monitor_trash (loop);

    /* This doesn't work ... */
    g_idle_add ((GSourceFunc) trash_test_file, NULL);

    /* ... but this does */
    // g_timeout_add (50, (GSourceFunc) trash_test_file, NULL);

    g_timeout_add_seconds (10, (GSourceFunc) fail_quit, loop);

    g_main_loop_run (loop);
}
