#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <glib.h>
#include <gio/gio.h>

GMainLoop *loop;

static void umount_cb(GObject *source, GAsyncResult *res, void *udata)
{
    GMount *f = G_MOUNT(source);
    GError *error = NULL;

    printf("unmount finishing\n");
    g_mount_unmount_finish(f, res, &error);
    if (error) {
        printf("unmount error: %s\n", error->message);
        g_error_free(error);
        error = NULL;
    }
    printf("unmount finished\n\n");
    g_main_loop_quit(loop);
}

static void info_cb(GObject *source, GAsyncResult *res, void *udata)
{
    GError *error = NULL;
    GFile *f = G_FILE(source);
    printf("query info finishing\n");
    GFileInfo *info = g_file_query_info_finish(f, res, &error);
    if (error) {
        printf("query error: %s\n", error->message);
        g_error_free(error);
        error = NULL;
    }
    printf("query info finished\n");
}

static void mount_cb(GObject *source, GAsyncResult *res, void *udata)
{
    GFile *f = G_FILE(source);
    GError *error = NULL;
    GMount *mount;
    printf("mount finishing\n");
    g_file_mount_enclosing_volume_finish(f, res, &error);
    if (error) {
        printf("mount error: %s\n", error->message);
        g_error_free(error);
        error = NULL;
    }
    printf("mount finished\n");
    sleep(5);

    printf("finding enclosing mount\n");
    mount = g_file_find_enclosing_mount(f, NULL, &error);
    if (error) {
        printf("find error: %s\n", error->message);
        g_error_free(error);
        error = NULL;
    }
    printf("finding enclosing mount finished\n");

    printf("unmount starting\n");
    g_mount_unmount(mount, G_MOUNT_UNMOUNT_NONE,
                                            NULL, umount_cb, NULL);

    printf("query info starting\n");
    g_file_query_info_async(f, "*", 0, 0, NULL, info_cb, NULL);
}

void test_read(char *uri)
{
    GFile *f = g_file_new_for_uri(uri);
    printf("mount starting\n");
    g_file_mount_enclosing_volume(f, G_MOUNT_MOUNT_NONE, NULL, NULL, mount_cb,
                                  NULL);
    g_main_loop_run(loop);
    g_object_unref(f);
}

int main(int argc, char **argv)
{
    loop = g_main_loop_new(NULL, FALSE);
    for (;;) {
        test_read(argv[1]);
        sleep(5);
    }
    return 0;
}
