#include <libgnomevfs/gnome-vfs-dns-sd.h>
#include <glib/gstdio.h>

void resolver_callback(GnomeVFSDNSSDResolveHandle *handle G_GNUC_UNUSED,
    GnomeVFSResult result, const GnomeVFSDNSSDService *service,
    const char *host, int port, const GHashTable *text G_GNUC_UNUSED, 
    int text_raw_len G_GNUC_UNUSED, const char *text_raw G_GNUC_UNUSED, 
    gpointer callback_data G_GNUC_UNUSED)
{
    g_printf("async: %s (%s:%d) [%s]\n", 
            service ? service->name : NULL, host, port,
            gnome_vfs_result_to_string(result));
}

static void browse_callback(GnomeVFSDNSSDBrowseHandle *handle G_GNUC_UNUSED,
                            GnomeVFSDNSSDServiceStatus status,
                            const GnomeVFSDNSSDService *service,
                            gpointer callback_data G_GNUC_UNUSED)
{
    GnomeVFSDNSSDResolveHandle *resolver = NULL;
    GnomeVFSResult result;
    gchar *host = NULL;
    gint port = 0;
    
    switch(status) {
        case GNOME_VFS_DNS_SD_SERVICE_ADDED:
            result = gnome_vfs_dns_sd_resolve_sync(
                    service->name, service->type, service->domain, 0,
                    &host, &port, NULL, NULL, NULL);

            g_printf("added: %s (%s:%d) [%s]\n", 
                    service->name, host, port,
                    gnome_vfs_result_to_string(result));

            gnome_vfs_dns_sd_resolve(
                    &resolver, service->name, service->type, service->domain,
                    0, resolver_callback, NULL, NULL);

            break;
            
        case GNOME_VFS_DNS_SD_SERVICE_REMOVED:
            g_printf("removed: %s\n", service->name);
            break;
    }
    
    g_free(host);
}

int main() 
{
    GList *domains, *iter;

    g_type_init();

    domains = gnome_vfs_get_default_browse_domains();
    domains = g_list_prepend(domains, "local");

    for(iter = domains; iter; iter = iter->next) {
        GnomeVFSDNSSDBrowseHandle *browser = NULL;
        const gchar *domain = (const gchar*) iter->data;
        GnomeVFSResult result = gnome_vfs_dns_sd_browse(
                &browser, domain, "_ssh._tcp", browse_callback,
                NULL, NULL);

        if (GNOME_VFS_OK != result)
            g_warning("Cannot browse domain %s: %s\n",
                    domain, gnome_vfs_result_to_string(result));
    }
    
    domains = g_list_delete_link(domains, domains);
    g_list_foreach(domains, (GFunc) g_free, NULL);
    g_list_free(domains);
    
    g_main_loop_run(g_main_loop_new(NULL, TRUE));

    return 0;
}

// vim: sw=4 sta et
