
#include <stdio.h>
#include <glib.h>
#include <gio/gio.h>
#include <string.h>
#include <stdlib.h>

GDBusObjectManager *client;

static void
object_added (GDBusObjectManagerClient *_client,
              GObject *modem_object,
              gpointer unused)
{
	g_print ("An object was added\n");
}

static void
object_removed (GDBusObjectManagerClient *_client,
                GObject *modem_object,
                gpointer unused)
{
	g_print ("An object was removed\n");
}

static void
name_owner_changed (GDBusObjectManagerClient *_client,
                    GParamSpec *pspec,
                    gpointer unused)
{
	gchar *name_owner;

	/* Valid name owner? */
	name_owner = g_dbus_object_manager_client_get_name_owner (_client);
	if (!name_owner) {
		g_print ("ModemManager disappeared from bus\n");
		return;
	}

	g_print ("ModemManager available in bus (%s)\n", name_owner);

	g_free (name_owner);
}

static gboolean
start_cb (gpointer unused)
{
    GError *error = NULL;

    client = g_dbus_object_manager_client_new_for_bus_sync (G_BUS_TYPE_SYSTEM,
                                                            G_DBUS_OBJECT_MANAGER_CLIENT_FLAGS_DO_NOT_AUTO_START,
                                                            "org.freedesktop.ModemManager1",
                                                            "/org/freedesktop/ModemManager1",
                                                            NULL,
                                                            NULL,
                                                            NULL,
                                                            NULL,
                                                            &error);

    if (!client) {
	    g_printerr ("Error creating client: %s\n", error->message);
	    exit (1);
    }

    g_signal_connect (client,
                      "notify::name-owner",
                      G_CALLBACK (name_owner_changed),
                      NULL);

    g_signal_connect (client,
                      "object-added",
                      G_CALLBACK (object_added),
                      NULL);

    g_signal_connect (client,
                      "object-removed",
                      G_CALLBACK (object_removed),
                      NULL);
    return FALSE;
}

int main (int argc, char **argv)
{
    GMainLoop *loop;

    g_type_init ();

    g_timeout_add_seconds (1, start_cb, NULL);

    loop = g_main_loop_new (NULL, FALSE);

    g_main_loop_run (loop);

    return 0;
}
