/* gcc -o /tmp/c gdu_pool_crash.c -Wall `pkg-config --cflags --libs glib-2.0 gio-2.0 gdu` && /tmp/c
 * mkdir /tmp/d
 * while true; do sudo mount -o loop download/ubuntu/precise-desktop-amd64.iso /tmp/d; sudo umount /tmp/d; done
 */
#include <stdio.h>
#include <gio/gio.h>

#define GDU_API_IS_SUBJECT_TO_CHANGE
#include <gdu/gdu.h>

void
on_volume_added (GVolumeMonitor* monitor, GVolume* volume, gpointer user_data)
{
    char* device = g_volume_get_identifier(volume, G_VOLUME_IDENTIFIER_KIND_UNIX_DEVICE);
    GduPool* pool;
    GduDevice* gdu_device;

    if (device == NULL) {
        printf ("volume added: NULL\n");
        return;
    }
    printf ("volume added: %s\n", device);

    pool = gdu_pool_new();
    gdu_device = gdu_pool_get_by_device_file(pool, device);
    if (gdu_device == NULL) {
        printf ("gdu_pool_get_by_device_file returned NULL\n");
        goto out;
    }

    printf ("gdu_device: devname %s removable %i optical disk: %i\n",
            gdu_device_get_device_file (gdu_device),
            gdu_device_is_removable (gdu_device),
            gdu_device_is_optical_disc (gdu_device));

out:
    g_free (device);
}

void
on_volume_removed (GVolumeMonitor* monitor, GVolume* volume, gpointer user_data)
{
    char* device = g_volume_get_identifier(volume, G_VOLUME_IDENTIFIER_KIND_UNIX_DEVICE);

    if (device == NULL) {
        printf ("volume removed: NULL\n");
        return;
    }
    printf ("volume removed: %s\n", device);

    g_free (device);
}

int main()
{
    GVolumeMonitor* monitor;
    GMainLoop *ml;

    g_type_init();

    monitor = g_volume_monitor_get();
    g_signal_connect(monitor, "volume-added", G_CALLBACK (on_volume_added), NULL);
    g_signal_connect(monitor, "volume-removed", G_CALLBACK (on_volume_removed), NULL);

    ml = g_main_loop_new (NULL, FALSE);
    g_main_loop_run (ml);

    return 0;
}
