/*
 * Bluetooth, from BlueZ: turning it on and off, the devices paired with
 * this PC (connect, disconnect, remove, battery), and while the page is
 * open, looking for new ones to pair. While it's open the PC can also be
 * found by others (BlueZ turns that off again by itself after a few
 * minutes), and we are the pairing agent: PINs, passkeys and "does this
 * code match" are asked in dialogs.
 */
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <linux/rfkill.h>
#include <gio/gio.h>
#include "settings.h"
#include "rfkill.h"

#define BLUEZ "org.bluez"
#define ADAPTER BLUEZ ".Adapter1"
#define DEVICE BLUEZ ".Device1"
#define BATTERY BLUEZ ".Battery1"
#define AGENT_PATH "/org/cont8nuum/settings/agent"
#define SETTLE_MS 200
#define PAIR_TIMEOUT_MS 90000

static struct {
	GDBusObjectManager *om; // kept once made: the agent needs it too
	bool asking; // for om
	guint settle;
	bool discovering; // we asked the adapter to look
	bool made_visible; // we made it discoverable
	GHashTable *busy; // device path: what is being done to it
	struct c8ui_widget *page, *power, *status, *paired, *found_title, *found;
} bt;

/* The agent outlives the page: a pairing can still be asking */
static struct {
	guint id;
	GDBusMethodInvocation *pending; // waiting for the dialog
	struct c8ui_widget *dialog, *entry;
	bool numeric; // the entry wants a passkey, not a PIN
} agent;

/* Reading what BlueZ has */

static GDBusProxy *iface_of(GDBusObject *obj, const char *iface) {
	GDBusInterface *i = g_dbus_object_get_interface(obj, iface);
	return i ? G_DBUS_PROXY(i) : NULL; // a reference
}

static GDBusProxy *adapter(void) {
	if (bt.om == NULL) {
		return NULL;
	}
	GDBusProxy *found = NULL;
	GList *objects = g_dbus_object_manager_get_objects(bt.om);
	for (GList *l = objects; l && !found; l = l->next) {
		found = iface_of(l->data, ADAPTER);
	}
	g_list_free_full(objects, g_object_unref);
	return found;
}

static bool prop_bool(GDBusProxy *p, const char *name) {
	GVariant *v = g_dbus_proxy_get_cached_property(p, name);
	bool b = v && g_variant_is_of_type(v, G_VARIANT_TYPE_BOOLEAN) &&
		g_variant_get_boolean(v);
	if (v) {
		g_variant_unref(v);
	}
	return b;
}

static char *prop_string(GDBusProxy *p, const char *name) {
	GVariant *v = g_dbus_proxy_get_cached_property(p, name);
	char *s = v && g_variant_is_of_type(v, G_VARIANT_TYPE_STRING) ?
		g_variant_dup_string(v, NULL) : NULL;
	if (v) {
		g_variant_unref(v);
	}
	return s;
}

static int prop_int(GDBusProxy *p, const char *name, int def) {
	GVariant *v = p ? g_dbus_proxy_get_cached_property(p, name) : NULL;
	int n = def;
	if (v && g_variant_is_of_type(v, G_VARIANT_TYPE_BYTE)) {
		n = g_variant_get_byte(v);
	} else if (v && g_variant_is_of_type(v, G_VARIANT_TYPE_INT16)) {
		n = g_variant_get_int16(v);
	}
	if (v) {
		g_variant_unref(v);
	}
	return n;
}

/* What kind of thing it is, from its freedesktop icon name */
static const char *kind(const char *icon) {
	static const struct {
		const char *icon, *word;
	} kinds[] = {
		{ "audio-headset", "Headset" },
		{ "audio-headphones", "Headphones" },
		{ "audio-card", "Speaker" },
		{ "input-keyboard", "Keyboard" },
		{ "input-mouse", "Mouse" },
		{ "input-tablet", "Pen tablet" },
		{ "input-gaming", "Game controller" },
		{ "phone", "Phone" },
		{ "computer", "Computer" },
		{ "camera-video", "Camera" },
		{ "camera-photo", "Camera" },
		{ "printer", "Printer" },
		{ "network-wireless", "Network" },
	};
	for (size_t i = 0; icon && i < G_N_ELEMENTS(kinds); i++) {
		if (strcmp(icon, kinds[i].icon) == 0) {
			return kinds[i].word;
		}
	}
	return NULL;
}

struct device {
	char *path, *name, *icon;
	bool paired, connected, named;
	int battery, rssi;
};

static void device_clear(gpointer data) {
	struct device *d = data;
	g_free(d->path);
	g_free(d->name);
	g_free(d->icon);
}

static int by_order(gconstpointer a, gconstpointer b) {
	const struct device *x = a, *y = b;
	if (x->connected != y->connected) {
		return x->connected ? -1 : 1;
	}
	/* Ones found nearby: the closest first */
	if (!x->paired && !y->paired && x->rssi != y->rssi) {
		return x->rssi > y->rssi ? -1 : 1;
	}
	return g_utf8_collate(x->name, y->name);
}

static GArray *devices(void) {
	GArray *list = g_array_new(FALSE, TRUE, sizeof(struct device));
	g_array_set_clear_func(list, device_clear);
	if (bt.om == NULL) {
		return list;
	}
	GList *objects = g_dbus_object_manager_get_objects(bt.om);
	for (GList *l = objects; l; l = l->next) {
		GDBusProxy *dev = iface_of(l->data, DEVICE);
		if (dev == NULL) {
			continue;
		}
		GDBusProxy *bat = iface_of(l->data, BATTERY);
		struct device d = {
			.path = g_strdup(g_dbus_object_get_object_path(l->data)),
			.name = prop_string(dev, "Alias"),
			.icon = prop_string(dev, "Icon"),
			.paired = prop_bool(dev, "Paired") || prop_bool(dev, "Bonded"),
			.connected = prop_bool(dev, "Connected"),
			.battery = prop_int(bat, "Percentage", -1),
			.rssi = prop_int(dev, "RSSI", -1000),
		};
		/* Without a name it's only an address: not worth offering */
		char *name = prop_string(dev, "Name");
		d.named = name != NULL;
		g_free(name);
		if (d.name == NULL) {
			d.name = g_strdup("Device");
		}
		g_array_append_val(list, d);
		g_clear_object(&bat);
		g_object_unref(dev);
	}
	g_list_free_full(objects, g_object_unref);
	g_array_sort(list, by_order);
	return list;
}

/* Doing things */

static void rebuild(void);

static bool quiet_error(GError *error) {
	/* Cancelled by someone, not worth a dialog */
	const char *remote = g_dbus_error_get_remote_error(error);
	bool quiet = remote && (strstr(remote, "Canceled") ||
		strstr(remote, "AuthenticationCanceled"));
	g_free((char *)remote);
	return quiet || g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED);
}

static void error_text(const char *title, GError *error) {
	if (quiet_error(error)) {
		return;
	}
	g_dbus_error_strip_remote_error(error);
	show_error(title, error->message);
}

struct call {
	char *path, *busy; // what it's called on, what shows it
	const char *what; // "Couldn't connect", …
	bool then_connect; // a pairing: trust it and connect after
};

static void call_device(const char *path, const char *busy,
		const char *iface, const char *method, GVariant *args,
		const char *doing, const char *what, bool then_connect, int timeout);

static void called(GObject *source, GAsyncResult *res, gpointer data) {
	struct call *c = data;
	GError *error = NULL;
	GVariant *r = g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), res,
		&error);
	g_hash_table_remove(bt.busy, c->busy);
	if (r) {
		g_variant_unref(r);
		if (c->then_connect) {
			/* Paired: let it come back by itself, and connect now */
			g_dbus_connection_call(G_DBUS_CONNECTION(source), BLUEZ, c->path,
				"org.freedesktop.DBus.Properties", "Set",
				g_variant_new("(ssv)", DEVICE, "Trusted",
				g_variant_new_boolean(TRUE)), NULL, G_DBUS_CALL_FLAGS_NONE,
				-1, NULL, NULL, NULL);
			call_device(c->path, c->path, DEVICE, "Connect", NULL,
				"Connecting…",
				"Couldn't connect", false, 30000);
		}
	} else {
		error_text(c->what, error);
		g_error_free(error);
	}
	g_free(c->path);
	g_free(c->busy);
	g_free(c);
	rebuild();
}

static GDBusConnection *system_bus(void) {
	return g_dbus_object_manager_client_get_connection(
		G_DBUS_OBJECT_MANAGER_CLIENT(bt.om));
}

static void call_device(const char *path, const char *busy,
		const char *iface, const char *method, GVariant *args,
		const char *doing, const char *what, bool then_connect, int timeout) {
	if (bt.om == NULL) {
		return;
	}
	struct call *c = g_new0(struct call, 1);
	c->path = g_strdup(path);
	c->busy = g_strdup(busy);
	c->what = what;
	c->then_connect = then_connect;
	g_hash_table_insert(bt.busy, g_strdup(busy), (gpointer)doing);
	g_dbus_connection_call(system_bus(), BLUEZ, path, iface, method, args,
		NULL, G_DBUS_CALL_FLAGS_NONE, timeout, NULL, called, c);
	rebuild();
}

static void set_adapter(const char *name, bool value) {
	GDBusProxy *a = adapter();
	if (a == NULL) {
		return;
	}
	g_dbus_connection_call(system_bus(), BLUEZ, g_dbus_proxy_get_object_path(a),
		"org.freedesktop.DBus.Properties", "Set", g_variant_new("(ssv)",
		ADAPTER, name, g_variant_new_boolean(value)), NULL,
		G_DBUS_CALL_FLAGS_NONE, 5000, NULL, NULL, NULL);
	g_object_unref(a);
}

static void adapter_call(const char *method) {
	GDBusProxy *a = adapter();
	if (a == NULL) {
		return;
	}
	g_dbus_connection_call(system_bus(), BLUEZ, g_dbus_proxy_get_object_path(a),
		ADAPTER, method, NULL, NULL, G_DBUS_CALL_FLAGS_NONE, 5000, NULL, NULL,
		NULL);
	g_object_unref(a);
}

static void path_gone(struct c8ui_widget *w, void *data) {
	g_free(w->user_data);
}

static void do_connect(struct c8ui_widget *w, void *data) {
	call_device(w->user_data, w->user_data, DEVICE, "Connect", NULL,
		"Connecting…",
		"Couldn't connect", false, 30000);
}

static void do_disconnect(struct c8ui_widget *w, void *data) {
	call_device(w->user_data, w->user_data, DEVICE, "Disconnect", NULL,
		"Disconnecting…",
		"Couldn't disconnect", false, 10000);
}

static void do_pair(struct c8ui_widget *w, void *data) {
	call_device(w->user_data, w->user_data, DEVICE, "Pair", NULL,
		"Pairing…",
		"Couldn't pair", true, PAIR_TIMEOUT_MS);
}

static void do_remove(struct c8ui_widget *w, void *data) {
	GDBusProxy *a = adapter();
	if (a == NULL) {
		return;
	}
	call_device(g_dbus_proxy_get_object_path(a), w->user_data, ADAPTER,
		"RemoveDevice", g_variant_new("(o)", (char *)w->user_data),
		"Removing…", "Couldn't remove the device", false, 10000);
	g_object_unref(a);
}

/* Showing it */

static struct c8ui_widget *button(const char *label, c8ui_action_fn fn,
		const char *path, bool disabled) {
	struct c8ui_widget *b = c8ui_button_new(label, fn, NULL);
	b->user_data = g_strdup(path);
	b->on_destroy = path_gone;
	c8ui_widget_set_disabled(b, disabled);
	return b;
}

static struct c8ui_widget *device_row(const struct device *d) {
	struct c8ui_widget *row = c8ui_box_new(C8UI_HORIZONTAL, 12);
	struct c8ui_widget *text = c8ui_box_new(C8UI_VERTICAL, 2);
	text->fixed_width = 340;
	c8ui_widget_add(text, c8ui_label_new(d->named ?
		c8_stealth_alias(C8_STEALTH_DEVICE, d->name) : d->name,
		C8UI_TEXT_BODY));

	const char *doing = g_hash_table_lookup(bt.busy, d->path);
	GString *line = g_string_new(kind(d->icon));
	const char *state = doing ? doing : d->connected ? "Connected" :
		d->paired ? "Not connected" : NULL;
	if (state) {
		g_string_append_printf(line, "%s%s", line->len ? " · " : "", state);
	}
	if (d->battery >= 0 && d->connected) {
		g_string_append_printf(line, " · Battery %d%%", d->battery);
	}
	if (line->len) {
		c8ui_widget_add(text, caption(line->str));
	}
	g_string_free(line, TRUE);
	c8ui_widget_add(row, text);

	if (d->paired) {
		c8ui_widget_add(row, d->connected ?
			button("Disconnect", do_disconnect, d->path, doing != NULL) :
			button("Connect", do_connect, d->path, doing != NULL));
		c8ui_widget_add(row, button("Remove", do_remove, d->path,
			doing != NULL));
	} else {
		c8ui_widget_add(row, button("Pair", do_pair, d->path, doing != NULL));
	}
	return row;
}

static void rebuild(void) {
	if (bt.page == NULL) {
		return;
	}
	GDBusProxy *a = adapter();
	bool powered = a && prop_bool(a, "Powered");
	bool blocked = rfkill_blocked(RFKILL_TYPE_BLUETOOTH);
	c8ui_toggle_set(bt.power, powered);
	c8ui_widget_set_disabled(bt.power, a == NULL && !blocked);
	bt.power->hidden = a == NULL && !blocked;

	if (a == NULL) {
		c8ui_label_set_text(bt.status, blocked ? "Bluetooth is off. "
			"(Airplane mode turns it off too.)" : bt.om ?
			"This PC has no Bluetooth." : "Bluetooth isn't running "
			"(the bluetooth service).");
	} else if (!powered) {
		c8ui_label_set_text(bt.status, "Turn Bluetooth on to use your "
			"devices and find new ones.");
	} else {
		char *alias = prop_string(a, "Alias");
		char *text = g_strdup_printf("While this page is open, Bluetooth "
			"devices nearby can find this PC as “%s”.", alias ?
			c8_stealth_alias(C8_STEALTH_DEVICE, alias) : "");
		c8ui_label_set_text(bt.status, text);
		g_free(text);
		g_free(alias);
	}

	/* Looking only while it's on and the page is open */
	if (powered && !bt.discovering) {
		bt.discovering = true;
		adapter_call("StartDiscovery");
		if (!prop_bool(a, "Discoverable")) {
			bt.made_visible = true;
			set_adapter("Discoverable", true);
		}
	} else if (!powered) {
		bt.discovering = false;
	}

	c8ui_widget_clear(bt.paired);
	c8ui_widget_clear(bt.found);
	GArray *list = devices();
	int paired = 0, found = 0;
	for (guint i = 0; i < list->len; i++) {
		struct device *d = &g_array_index(list, struct device, i);
		if (d->paired) {
			add(bt.paired, device_row(d));
			paired++;
		} else if (powered && (d->named ||
				g_hash_table_contains(bt.busy, d->path))) {
			add(bt.found, device_row(d));
			found++;
		}
	}
	g_array_free(list, TRUE);
	if (paired == 0) {
		add(bt.paired, caption("No devices are paired with this PC yet."));
	}
	bt.found_title->hidden = !powered;
	bt.found->hidden = !powered;
	if (powered && found == 0) {
		add(bt.found, caption(prop_bool(a, "Discovering") ?
			"Looking for devices… Make sure the device is on and can be "
			"found (often by holding its Bluetooth or power button)." :
			"Nothing found."));
	}
	g_clear_object(&a);
	c8ui_widget_queue_layout(bt.page);
}

static gboolean settled(gpointer data) {
	bt.settle = 0;
	rebuild();
	return G_SOURCE_REMOVE;
}

/* Discovery changes RSSI all the time: rebuild when it's quiet a moment */
static void om_changed(void) {
	if (bt.settle == 0) {
		bt.settle = g_timeout_add(SETTLE_MS, settled, NULL);
	}
}

static void object_changed(GDBusObjectManager *om, GDBusObject *obj,
		gpointer data) {
	om_changed();
}

static void iface_changed(GDBusObjectManager *om, GDBusObject *obj,
		GDBusInterface *iface, gpointer data) {
	om_changed();
}

static void props_changed(GDBusObjectManagerClient *om, GDBusObjectProxy *obj,
		GDBusProxy *iface, GVariant *changed, const char *const *invalidated,
		gpointer data) {
	/* Only RSSI moved: no need to show it again */
	GVariant *rssi = g_variant_lookup_value(changed, "RSSI", NULL);
	bool only = rssi && g_variant_n_children(changed) == 1;
	g_clear_pointer(&rssi, g_variant_unref);
	if (only) {
		return;
	}
	om_changed();
}

static void agent_start(GDBusConnection *bus);

/* BlueZ (re)started or went: look again, be its agent again */
static void owner_changed(GObject *om, GParamSpec *spec, gpointer data) {
	bt.discovering = false;
	char *owner = g_dbus_object_manager_client_get_name_owner(
		G_DBUS_OBJECT_MANAGER_CLIENT(om));
	if (owner) {
		agent_start(system_bus());
	}
	g_free(owner);
	om_changed();
}

static void radios_changed(void *data) {
	om_changed();
}

/* Pairing agent */

static const char agent_xml[] =
	"<node><interface name='org.bluez.Agent1'>"
	"<method name='Release'/>"
	"<method name='RequestPinCode'><arg type='o' direction='in'/>"
	"<arg type='s' direction='out'/></method>"
	"<method name='DisplayPinCode'><arg type='o' direction='in'/>"
	"<arg type='s' direction='in'/></method>"
	"<method name='RequestPasskey'><arg type='o' direction='in'/>"
	"<arg type='u' direction='out'/></method>"
	"<method name='DisplayPasskey'><arg type='o' direction='in'/>"
	"<arg type='u' direction='in'/><arg type='q' direction='in'/></method>"
	"<method name='RequestConfirmation'><arg type='o' direction='in'/>"
	"<arg type='u' direction='in'/></method>"
	"<method name='RequestAuthorization'><arg type='o' direction='in'/>"
	"</method>"
	"<method name='AuthorizeService'><arg type='o' direction='in'/>"
	"<arg type='s' direction='in'/></method>"
	"<method name='Cancel'/>"
	"</interface></node>";

static void reject(GDBusMethodInvocation *inv, bool cancelled) {
	g_dbus_method_invocation_return_dbus_error(inv, cancelled ?
		"org.bluez.Error.Canceled" : "org.bluez.Error.Rejected",
		cancelled ? "Cancelled" : "Rejected");
}

static char *device_name(const char *path) {
	GDBusObject *obj = bt.om ? g_dbus_object_manager_get_object(bt.om, path) :
		NULL;
	GDBusProxy *dev = obj ? iface_of(obj, DEVICE) : NULL;
	char *name = dev ? prop_string(dev, "Alias") : NULL;
	g_clear_object(&dev);
	g_clear_object(&obj);
	if (name && c8_stealth()) { // pairing asks name it
		char *shown = g_strdup(c8_stealth_alias(C8_STEALTH_DEVICE, name));
		g_free(name);
		return shown;
	}
	return name ? name : g_strdup("the device");
}

/* The dialog going, answered or not (unless another replaced it) */
static void agent_dialog_gone(struct c8ui_widget *w, void *data) {
	if (agent.dialog != w) {
		return;
	}
	agent.dialog = agent.entry = NULL;
	if (agent.pending) {
		reject(agent.pending, true);
		agent.pending = NULL;
	}
}

static void agent_answered(int choice, void *data) {
	GDBusMethodInvocation *inv = agent.pending;
	agent.pending = NULL;
	if (inv == NULL) {
		return; // only showing a code
	}
	if (choice != 0) {
		reject(inv, choice < 0);
		return;
	}
	if (agent.entry == NULL) {
		g_dbus_method_invocation_return_value(inv, NULL);
		return;
	}
	const char *text = c8ui_entry_get(agent.entry);
	if (agent.numeric) {
		char *end;
		unsigned long n = strtoul(text, &end, 10);
		if (*text == '\0' || *end || n > 999999) {
			reject(inv, false);
			return;
		}
		g_dbus_method_invocation_return_value(inv,
			g_variant_new("(u)", (guint32)n));
	} else {
		g_dbus_method_invocation_return_value(inv, g_variant_new("(s)", text));
	}
}

static void agent_close(void) {
	if (agent.dialog) {
		c8ui_dialog_close(agent.dialog);
	}
}

static void agent_entered(struct c8ui_widget *w, void *data) {
	if (agent.dialog) {
		c8ui_dialog_choose(agent.dialog, 0);
	}
}

/* A dialog for inv (NULL: nothing to answer); buttons: Yes/No, OK/Cancel
 * or just Cancel */
static void agent_ask(GDBusMethodInvocation *inv, const char *title,
		const char *message, const char *const *buttons, int count,
		const char *entry) {
	agent_close();
	agent.pending = NULL; // closing it answered the last one
	if (app.root == NULL) {
		if (inv) {
			reject(inv, false);
		}
		return;
	}
	agent.pending = inv;
	agent.dialog = c8ui_dialog_show(app.root, title, message, buttons, count,
		agent_answered, NULL);
	agent.dialog->on_destroy = agent_dialog_gone;
	if (entry) {
		agent.entry = c8ui_entry_new(entry, "", agent_entered, NULL);
		c8ui_dialog_add(agent.dialog, agent.entry);
		c8ui_widget_grab_focus(agent.entry);
	}
}

static void agent_call(GDBusConnection *bus, const char *sender,
		const char *path, const char *iface, const char *method,
		GVariant *params, GDBusMethodInvocation *inv, gpointer data) {
	static const char *const ok_cancel[] = { "OK", "Cancel" };
	static const char *const yes_no[] = { "Yes", "No" };
	static const char *const cancel[] = { "Cancel" };
	const char *dev = NULL;
	if (g_variant_n_children(params) > 0) {
		g_variant_get_child(params, 0, "&o", &dev);
	}
	char *name = dev ? device_name(dev) : NULL;
	char *msg = NULL;
	if (strcmp(method, "RequestPinCode") == 0) {
		msg = g_strdup_printf("Type the PIN for %s. It's often 0000 or "
			"1234, or written on the device.", name);
		agent.numeric = false;
		agent_ask(inv, "Pair a device", msg, ok_cancel, 2, "PIN");
	} else if (strcmp(method, "RequestPasskey") == 0) {
		msg = g_strdup_printf("Type the passcode shown on %s.", name);
		agent.numeric = true;
		agent_ask(inv, "Pair a device", msg, ok_cancel, 2, "Passcode");
	} else if (strcmp(method, "DisplayPinCode") == 0) {
		const char *pin;
		g_variant_get(params, "(&o&s)", NULL, &pin);
		msg = g_strdup_printf("Type %s on %s, then press Enter on it.", pin,
			name);
		g_dbus_method_invocation_return_value(inv, NULL);
		agent_ask(NULL, "Pair a device", msg, cancel, 1, NULL);
	} else if (strcmp(method, "DisplayPasskey") == 0) {
		guint32 key;
		guint16 typed;
		g_variant_get(params, "(&ouq)", NULL, &key, &typed);
		msg = g_strdup_printf("Type %06u on %s, then press Enter on it.",
			key, name);
		g_dbus_method_invocation_return_value(inv, NULL);
		if (agent.dialog && agent.pending == NULL) {
			c8ui_dialog_set_message(agent.dialog, msg); // a key was typed
		} else {
			agent_ask(NULL, "Pair a device", msg, cancel, 1, NULL);
		}
	} else if (strcmp(method, "RequestConfirmation") == 0) {
		guint32 key;
		g_variant_get(params, "(&ou)", NULL, &key);
		msg = g_strdup_printf("Does %s show this code?\n%06u", name, key);
		agent_ask(inv, "Pair a device", msg, yes_no, 2, NULL);
	} else if (strcmp(method, "RequestAuthorization") == 0) {
		msg = g_strdup_printf("Do you want to pair with %s?", name);
		agent_ask(inv, "Pair a device", msg, yes_no, 2, NULL);
	} else if (strcmp(method, "AuthorizeService") == 0) {
		/* A paired device using one more of its services: fine */
		GDBusObject *obj = bt.om && dev ?
			g_dbus_object_manager_get_object(bt.om, dev) : NULL;
		GDBusProxy *d = obj ? iface_of(obj, DEVICE) : NULL;
		bool paired = d && prop_bool(d, "Paired");
		g_clear_object(&d);
		g_clear_object(&obj);
		if (paired) {
			g_dbus_method_invocation_return_value(inv, NULL);
		} else {
			reject(inv, false);
		}
	} else if (strcmp(method, "Cancel") == 0) {
		g_dbus_method_invocation_return_value(inv, NULL);
		if (agent.pending) {
			reject(agent.pending, true); // BlueZ stopped waiting
			agent.pending = NULL;
		}
		agent_close();
	} else {
		g_dbus_method_invocation_return_value(inv, NULL); // Release
	}
	g_free(msg);
	g_free(name);
}

static const GDBusInterfaceVTable agent_vtable = { agent_call, NULL, NULL };

static void agent_registered(GObject *source, GAsyncResult *res, gpointer data) {
	GVariant *r = g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), res,
		NULL);
	if (r) {
		g_variant_unref(r);
		g_dbus_connection_call(G_DBUS_CONNECTION(source), BLUEZ, "/org/bluez",
			BLUEZ ".AgentManager1", "RequestDefaultAgent",
			g_variant_new("(o)", AGENT_PATH), NULL, G_DBUS_CALL_FLAGS_NONE,
			-1, NULL, NULL, NULL);
	}
}

static void agent_start(GDBusConnection *bus) {
	if (agent.id == 0) {
		GDBusNodeInfo *info = g_dbus_node_info_new_for_xml(agent_xml, NULL);
		agent.id = g_dbus_connection_register_object(bus, AGENT_PATH,
			info->interfaces[0], &agent_vtable, NULL, NULL, NULL);
		g_dbus_node_info_unref(info);
	}
	/* Again whenever BlueZ (re)starts */
	g_dbus_connection_call(bus, BLUEZ, "/org/bluez", BLUEZ ".AgentManager1",
		"RegisterAgent", g_variant_new("(os)", AGENT_PATH, "KeyboardDisplay"),
		NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, agent_registered, NULL);
}

/* The page */

static void power_changed(struct c8ui_widget *w, void *data) {
	bool on = c8ui_toggle_get(w);
	if (on && rfkill_blocked(RFKILL_TYPE_BLUETOOTH)) {
		/* Blocked (Airplane mode): unblocking powers it as it was */
		rfkill_block(RFKILL_TYPE_BLUETOOTH, false);
	}
	set_adapter("Powered", on);
}

static void got_manager(GObject *source, GAsyncResult *res, gpointer data) {
	GError *error = NULL;
	GDBusObjectManager *om = g_dbus_object_manager_client_new_for_bus_finish(res,
		&error);
	bt.asking = false;
	if (om == NULL) {
		g_warning("Bluetooth: %s", error->message);
		g_error_free(error);
		rebuild();
		return;
	}
	bt.om = om;
	g_signal_connect(om, "object-added", G_CALLBACK(object_changed), NULL);
	g_signal_connect(om, "object-removed", G_CALLBACK(object_changed), NULL);
	g_signal_connect(om, "interface-added", G_CALLBACK(iface_changed), NULL);
	g_signal_connect(om, "interface-removed", G_CALLBACK(iface_changed), NULL);
	g_signal_connect(om, "interface-proxy-properties-changed",
		G_CALLBACK(props_changed), NULL);
	g_signal_connect(om, "notify::name-owner", G_CALLBACK(owner_changed),
		NULL);
	agent_start(system_bus());
	rebuild();
}

static void page_gone(struct c8ui_widget *w, void *data) {
	bt.page = bt.power = bt.status = bt.paired = bt.found = NULL;
	bt.found_title = NULL;
	rfkill_unlisten(radios_changed, NULL);
	if (bt.settle) {
		g_source_remove(bt.settle);
		bt.settle = 0;
	}
	if (bt.discovering) {
		adapter_call("StopDiscovery");
		bt.discovering = false;
	}
	if (bt.made_visible) {
		set_adapter("Discoverable", false);
		bt.made_visible = false;
	}
}

static void bluetooth_build(struct c8ui_widget *box) {
	if (bt.busy == NULL) {
		bt.busy = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
	}
	bt.page = c8ui_box_new(C8UI_VERTICAL, 18);
	bt.page->fill = true;
	bt.page->on_destroy = page_gone;
	add(box, bt.page);

	bt.power = c8ui_toggle_new(NULL, NULL, false, power_changed, NULL);
	add(bt.page, bt.power);
	bt.status = caption("");
	add(bt.page, bt.status);

	add(bt.page, section_title("Devices"));
	bt.paired = c8ui_box_new(C8UI_VERTICAL, 12);
	add(bt.page, bt.paired);

	bt.found_title = section_title("Add a device");
	add(bt.page, bt.found_title);
	bt.found = c8ui_box_new(C8UI_VERTICAL, 12);
	add(bt.page, bt.found);

	rfkill_listen(radios_changed, NULL);
	if (bt.om == NULL && !bt.asking) {
		bt.asking = true;
		g_dbus_object_manager_client_new_for_bus(G_BUS_TYPE_SYSTEM,
			G_DBUS_OBJECT_MANAGER_CLIENT_FLAGS_NONE, BLUEZ, "/", NULL, NULL,
			NULL, NULL, got_manager, NULL);
	}
	rebuild();
}

const struct page page_bluetooth = {
	.name = "bluetooth",
	.title = "Bluetooth",
	.build = bluetooth_build,
};
