/* Demonstrates that destroying a GDBusServer without calling
 * g_dbus_server_start() on it does not release the address it was bound to, so
 * subsequent attempts to listen on the same address will fail.
 */
#include <gio/gio.h>

GMainLoop *loop;

static gboolean
quit_main_loop (gpointer user_data)
{
  g_main_loop_quit (loop);
  return FALSE;
}

static void
create_server (gboolean start_before_stopping)
{
  gchar *guid = g_dbus_generate_guid ();
  GDBusServer *dbus_server;
  GError *error = NULL;

  dbus_server = g_dbus_server_new_sync (
      "unix:abstract=dbus-tube-test",
      G_DBUS_SERVER_FLAGS_NONE, guid, NULL, NULL, &error);
  g_assert_no_error (error);

  if (start_before_stopping)
    g_dbus_server_start (dbus_server);

  g_dbus_server_stop (dbus_server);
  g_object_unref (dbus_server);
  g_free (guid);

  /* Apparently we need to hit the main loop to give the first one a chance to
   * stop listening, even if we do start it. */
  g_idle_add (quit_main_loop, loop);
  g_main_loop_run (loop);
}

int
main (
    int argc,
    char *argv[])
{
  gboolean start_before_stopping =
      argc == 2 &&
      strcmp (argv[1], "--start-before-stopping") == 0;

  g_type_init ();
  loop = g_main_loop_new (NULL, FALSE);

  create_server (start_before_stopping);
  create_server (start_before_stopping);
  return 0;
}
