/*
 * c8-tailscale: Tailscale in the Metro style. A page list down the side
 * like PC settings: Status (connect, this device, warnings), Devices
 * (everything on the tailnet, each with a page of its own: copy its
 * address, ping it, send it a file), Exit node (the tailnet's own, or a
 * Mullvad one by country and city), Account (switch, add, log out). The
 * Search charm finds devices, the Settings charm has the preferences.
 * The live tile is tile.c's job; c8-tailscale-tile keeps it fresh while
 * this isn't open.
 */
#include <math.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <glib.h>
#include <xkbcommon/xkbcommon-keysyms.h>
#include <c8ui/c8ui.h>
#include <c8ui/c8ui-charms.h>
#include <c8ui/c8ui-files.h>
#include <c8ui/c8ui-wayland.h>
#include "stealth.h"
#include "tailscale.h"

#define ROW_H 64
#define POLL_S 5
#define POLL_LOGIN_S 2
#define TILE_DELAY_S 2
#define ADMIN_URL "https://login.tailscale.com/admin"

/* Below this the page list and the page take turns, a phone app's way:
 * the pane is PANE_WIDTH wide and a page needs about 440 beside it */
#define PANE_WIDTH 300

#define COLOR_ONLINE 0x60a917
#define COLOR_OFFLINE 0x647687

enum page {
	PAGE_STATUS,
	PAGE_DEVICES,
	PAGE_EXIT,
	PAGE_ACCOUNT,
	PAGE_COUNT,
};

static const char *const page_titles[PAGE_COUNT] = {
	"Status", "Devices", "Exit node", "Account",
};

static struct {
	struct c8ui_app *app;
	struct c8ui_window *win;
	struct c8ui_root *root;
	struct c8ui_widget *pages; // the list of pages and the one showing
	struct c8ui_widget *content; // that page, until it's built again
	struct c8ui_widget *appbar;
	struct c8ui_widget *cmd_refresh, *cmd_files, *cmd_copy, *cmd_ping,
		*cmd_send, *cmd_exit;
	struct c8ui_charms *charms;
	enum page page;
	bool page_given; // --page: open on it, narrow too
	char *device_id; // a device's page is showing (on the Devices page)
	char *filter; // the Devices search box
	char *fingerprint; // what the content was built from
	bool open_auth; // open the login page as soon as there is one
	int poll_s;
	guint tile_timer;
	/* What this build of the content needs kept until the next */
	GPtrArray *strings;
	GPtrArray *items; // struct ts_peer, the Devices list
	struct c8ui_widget *list, *connection, *traffic, *ping_out, *ping_ring;
	struct c8ui_widget *country, *city, *accounts_box;
	int mullvad_country; // the Mullvad combo's choice, to keep it
	GPtrArray *countries, *cities; // the combos' items (strings)
	/* The account list came after the page was built */
	GPtrArray *accounts;
} g;

static bool rebuild(bool force);
static void apply_theme(void);

/* Strings that live as long as the page */
static const char *keep(char *s) {
	g_ptr_array_add(g.strings, s);
	return s;
}

static const char *keepf(const char *fmt, ...) G_GNUC_PRINTF(1, 2);
static const char *keepf(const char *fmt, ...) {
	va_list ap;
	va_start(ap, fmt);
	char *s = g_strdup_vprintf(fmt, ap);
	va_end(ap);
	return keep(s);
}

/* The tile, a moment after things settle */

static gboolean tile_now(gpointer data) {
	g.tile_timer = 0;
	ts_tile_update(APP_ID);
	ts_tile_update(TILE_WIDGET_ID);
	return G_SOURCE_REMOVE;
}

static void tile_later(void) {
	if (g.tile_timer == 0) {
		g.tile_timer = g_timeout_add_seconds(TILE_DELAY_S, tile_now, NULL);
	}
}

/* Saying things */

static void show_message(const char *title, const char *message) {
	c8ui_dialog_message(g.root, title, message);
}

/* A command that changes something finished: say so only if it failed */
static void command_done(bool ok, const char *out, void *data) {
	if (!ok) {
		char *say = ts_shown_text(out);
		show_message(data ? data : "Tailscale couldn't do that",
			say[0] ? say : "It gave no reason.");
		g_free(say);
	}
}

static void copy_text(struct c8ui_widget *w, void *data) {
	if (g.root && data) {
		c8ui_root_set_clipboard(g.root, data);
	}
}

static void open_link(struct c8ui_widget *w, void *data) {
	if (g.win && data) {
		c8ui_window_open_uri(g.win, data);
	}
}

/* Page pieces, in PC settings' style */

static struct c8ui_widget *section_title(const char *text) {
	struct c8ui_widget *box = c8ui_box_new(C8UI_VERTICAL, 0);
	c8ui_box_set_padding(box, 0, 18, 0, 0);
	c8ui_widget_add(box, c8ui_label_new(text, C8UI_TEXT_SUBHEADER));
	return box;
}

static struct c8ui_widget *caption(const char *text) {
	struct c8ui_widget *l = c8ui_label_new(text, C8UI_TEXT_BODY);
	c8ui_label_set_color(l, C8UI_COLOR_SECONDARY);
	return l;
}

/* Name, value, Copy in rows; narrow, the name goes over the value so
 * the value keeps most of the width (the rows turn by themselves) */
static struct c8ui_widget *details_new(void) {
	struct c8ui_widget *rows = c8ui_box_new(C8UI_VERTICAL, 10);
	c8ui_box_set_narrow_spacing(rows, 14);
	rows->fill = true;
	return rows;
}

/* A row of the details: name, value and a Copy link when there is
 * something to copy (the real value, even in stealth mode: copying is
 * using it, not showing it) */
static struct c8ui_widget *detail(struct c8ui_widget *rows, const char *name,
		const char *value, const char *copy) {
	if (value == NULL || value[0] == '\0') {
		return NULL;
	}
	struct c8ui_widget *n = c8ui_label_new(name, C8UI_TEXT_BODY);
	c8ui_label_set_color(n, C8UI_COLOR_SECONDARY);
	n->fixed_width = 170;
	struct c8ui_widget *v = c8ui_label_new(value, C8UI_TEXT_BODY);
	c8ui_label_set_max_lines(v, 4);
	v->fill = true;
	v->expand = true;
	struct c8ui_widget *pair = c8ui_box_new(C8UI_HORIZONTAL, 24);
	c8ui_box_set_narrow_orientation(pair, C8UI_VERTICAL);
	c8ui_box_set_narrow_spacing(pair, 2);
	pair->expand = true;
	c8ui_widget_add(pair, n);
	c8ui_widget_add(pair, v);
	struct c8ui_widget *row = c8ui_box_new(C8UI_HORIZONTAL, 24);
	c8ui_box_set_narrow_spacing(row, 16);
	row->fill = true;
	c8ui_widget_add(row, pair);
	if (copy) {
		c8ui_widget_add(row, c8ui_link_new("Copy", copy_text,
			(void *)keep(g_strdup(copy))));
	}
	c8ui_widget_add(rows, row);
	return v;
}

static struct c8ui_widget *warning(enum c8ui_severity severity,
		const char *title, const char *message) {
	struct c8ui_widget *bar = c8ui_infobar_new(severity, title, message);
	bar->fill = true;
	bar->max_width = 760;
	return bar;
}

/* Status */

static void connect_toggled(struct c8ui_widget *w, void *data) {
	const char *up[] = { "up", NULL };
	const char *down[] = { "down", NULL };
	ts_control(c8ui_toggle_get(w) ? up : down, command_done,
		c8ui_toggle_get(w) ? "Couldn't connect" : "Couldn't disconnect");
}

static void login_done(bool ok, const char *out, void *data) {
	g.open_auth = false;
	command_done(ok, out, "Couldn't log in");
}

static void login_clicked(struct c8ui_widget *w, void *data) {
	g.open_auth = true;
	if (ts.auth_url) {
		open_link(NULL, ts.auth_url);
		g.open_auth = false;
	} else if (!ts_login(login_done, NULL)) {
		g.open_auth = false;
	}
	rebuild(true);
}

static void operator_clicked(struct c8ui_widget *w, void *data) {
	ts_become_operator(command_done, "Couldn't change the operator");
}

static void start_daemon(struct c8ui_widget *w, void *data) {
	char *systemctl = g_find_program_in_path("systemctl");
	if (systemctl == NULL) {
		show_message("Couldn't start Tailscale", "systemctl wasn't found.");
		return;
	}
	const char *argv[] = { "pkexec", systemctl, "enable", "--now",
		"tailscaled", NULL };
	if (!ts_run(argv, command_done, "Couldn't start Tailscale")) {
		show_message("Couldn't start Tailscale", "pkexec wasn't found.");
	}
	g_free(systemctl);
}

static void files_got(bool ok, const char *out, void *data) {
	char *text = g_strstrip(ts_shown_text(out));
	if (!ok) {
		show_message("Couldn't collect the files", text[0] ? text :
			"Tailscale gave no reason.");
	} else if (text[0]) {
		char *say = g_strdup_printf("Now in Downloads:\n%s", text);
		show_message("Files received", say);
		g_free(say);
	} else {
		show_message("No files waiting", "Nothing has been sent to this device "
			"since the last time.");
	}
	g_free(text);
}

/* Taildrop: move what was sent to this device into Downloads */
static void collect_files(struct c8ui_widget *w, void *data) {
	const char *dir = g_get_user_special_dir(G_USER_DIRECTORY_DOWNLOAD);
	if (dir == NULL) {
		dir = g_get_home_dir();
	}
	const char *args[] = { "file", "get", "--conflict=rename", "--verbose",
		dir, NULL };
	ts_control(args, files_got, NULL);
}

static void status_page(struct c8ui_widget *box) {
	if (ts.state == TS_NOT_INSTALLED) {
		c8ui_widget_add(box, warning(C8UI_SEVERITY_WARNING,
			"Tailscale isn't installed",
			"Install the tailscale package, then open this again."));
		return;
	}
	if (ts.state == TS_NO_DAEMON) {
		struct c8ui_widget *bar = warning(C8UI_SEVERITY_ERROR,
			"Tailscale isn't running", keep(ts_shown_text(ts.error)));
		c8ui_infobar_add_action(bar, "Start it", start_daemon, NULL);
		c8ui_widget_add(box, bar);
		c8ui_widget_add(box, caption("Starting it turns the tailscaled "
			"service on, now and at every boot."));
		return;
	}
	if (!ts.is_operator) {
		struct c8ui_widget *bar = warning(C8UI_SEVERITY_INFO,
			"Changes need a password",
			"Only root may control Tailscale on this PC. Allow yourself and "
			"it stops asking.");
		c8ui_infobar_add_action(bar, "Allow me", operator_clicked, NULL);
		c8ui_widget_add(box, bar);
	}
	for (int i = 0; ts.health && ts.health[i]; i++) {
		c8ui_widget_add(box, warning(C8UI_SEVERITY_WARNING, NULL,
			keep(ts_shown_text(ts.health[i]))));
	}

	if (ts.state == TS_NEEDS_LOGIN) {
		c8ui_widget_add(box, c8ui_label_new("This device isn't logged in to "
			"a tailnet yet.", C8UI_TEXT_ITEM));
		if (ts.auth_url) {
			c8ui_widget_add(box, caption("Finish logging in in your browser. "
				"This page follows along."));
			struct c8ui_widget *b = c8ui_button_new("Open the login page",
				open_link, (void *)keep(g_strdup(ts.auth_url)));
			c8ui_button_set_primary(b, true);
			c8ui_widget_add(box, b);
			struct c8ui_widget *url = caption(ts.auth_url);
			c8ui_label_set_max_lines(url, 2);
			c8ui_widget_add(box, url);
		} else if (ts_login_pending()) {
			struct c8ui_widget *row = c8ui_box_new(C8UI_HORIZONTAL, 12);
			struct c8ui_widget *ring = c8ui_ring_new(0);
			c8ui_ring_set_active(ring, true);
			c8ui_widget_add(row, ring);
			c8ui_widget_add(row, caption("Asking Tailscale where to log in…"));
			c8ui_widget_add(box, row);
		} else {
			struct c8ui_widget *b = c8ui_button_new("Log in", login_clicked, NULL);
			c8ui_button_set_primary(b, true);
			c8ui_widget_add(box, b);
		}
		return;
	}
	if (ts.state == TS_NEEDS_MACHINE_AUTH) {
		c8ui_widget_add(box, c8ui_label_new("Waiting for an admin to approve "
			"this device.", C8UI_TEXT_ITEM));
		c8ui_widget_add(box, c8ui_link_new("Open the admin console", open_link,
			(void *)ADMIN_URL));
		return;
	}

	bool on = ts.state == TS_RUNNING || ts.state == TS_STARTING;
	const char *state = ts.state == TS_RUNNING ? "Connected" :
		ts.state == TS_STARTING ? "Connecting…" : "Disconnected";
	c8ui_widget_add(box, c8ui_toggle_new("Tailscale", state, on,
		connect_toggled, NULL));

	c8ui_widget_add(box, section_title("This device"));
	struct c8ui_widget *grid = details_new();
	detail(grid, "Name", ts_shown_self(), NULL);
	detail(grid, "MagicDNS name", ts_shown_dns(ts.self_dns), ts.self_dns);
	detail(grid, "IPv4 address", ts_shown_ip(ts.self_ip4), ts.self_ip4);
	detail(grid, "IPv6 address", ts_shown_ip(ts.self_ip6), ts.self_ip6);
	if (ts.tailnet) {
		const char *tailnet = ts_shown_tailnet(ts.tailnet);
		detail(grid, "Tailnet", ts.user_login && g_strcmp0(ts.tailnet,
			ts.user_login) ? keepf("%s (%s)", tailnet,
			ts_shown_login(ts.user_login)) : tailnet, NULL);
	}
	struct ts_peer *exit = ts_exit_node();
	if (exit) {
		const char *where = exit->city ? keepf("%s, %s", exit->city,
			exit->country) : ts_shown_name(exit);
		detail(grid, "Exit node", keepf("%s%s", where, ts.exit_node_online ||
			exit->online ? "" : " (offline)"), NULL);
	} else if (ts.state == TS_RUNNING) {
		detail(grid, "Exit node", "None", NULL);
	}
	if (ts.state == TS_RUNNING) {
		int online, total;
		ts_count(&online, &total);
		detail(grid, "Devices", keepf("%d of %d online", online, total), NULL);
	}
	c8ui_widget_add(box, grid);

	c8ui_widget_add(box, section_title("Files sent to you"));
	c8ui_widget_add(box, caption("Other devices on your tailnet can send "
		"this one files. Collect them into Downloads."));
	c8ui_widget_add(box, c8ui_button_new("Collect received files",
		collect_files, NULL));
	if (ts.version) {
		c8ui_widget_add(box, c8ui_spacer_new(1, 12));
		c8ui_widget_add(box, caption(keepf("Tailscale %s", ts.version)));
	}
}

/* Devices */

static bool peer_matches(const struct ts_peer *p, const char *q) {
	if (q == NULL || q[0] == '\0') {
		return true;
	}
	/* What's shown is what's searched: in stealth mode a real name
	 * matching would give away whose it is */
	char *tags = ts_shown_text(p->tags);
	const char *fields[] = { ts_shown_name(p), ts_shown_dns(p->dns),
		ts_shown_ip(p->ip4), ts_shown_ip(p->ip6), ts_shown_owner(p->owner),
		p->os, tags };
	for (size_t i = 0; i < G_N_ELEMENTS(fields); i++) {
		if (fields[i]) {
			char *f = g_utf8_casefold(fields[i], -1);
			bool hit = strstr(f, q) != NULL;
			g_free(f);
			if (hit) {
				g_free(tags);
				return true;
			}
		}
	}
	g_free(tags);
	return false;
}

/* The peers to list: ours, matching the search box */
static void fill_items(void) {
	if (g.items == NULL) {
		return;
	}
	g_ptr_array_set_size(g.items, 0);
	char *q = g.filter ? g_utf8_casefold(g.filter, -1) : NULL;
	for (guint i = 0; ts.peers && i < ts.peers->len; i++) {
		struct ts_peer *p = ts.peers->pdata[i];
		if (!p->mullvad && peer_matches(p, q)) {
			g_ptr_array_add(g.items, p);
		}
	}
	g_free(q);
	if (g.list) {
		c8ui_list_set_count(g.list, g.items->len);
		c8ui_list_redraw(g.list);
	}
}

static void draw_device(struct c8ui_widget *list, cairo_t *cr,
		const struct c8ui_list_item *item, void *data) {
	if (item->index >= (int)g.items->len) {
		return;
	}
	struct ts_peer *p = g.items->pdata[item->index];
	const char *family = c8ui_widget_font(list);
	struct c8ui_rect r = item->rect;
	double pad = 12, dot = 10;
	/* A dot for the state */
	c8ui_set_source(cr, p->online ? COLOR_ONLINE : COLOR_OFFLINE, 1);
	cairo_arc(cr, r.x + pad + dot / 2, r.y + r.height / 2, dot / 2, 0,
		2 * G_PI);
	cairo_fill(cr);
	double x = r.x + pad + dot + 14;
	struct c8ui_font title = { 16, C8UI_WEIGHT_SEMIBOLD };
	struct c8ui_font small = c8ui_text_font(C8UI_TEXT_CAPTION);
	double th, ch, tw, cw;
	c8ui_text_size(family, title, "Ag", 0, 1, &tw, &th);
	c8ui_text_size(family, small, "Ag", 0, 1, &cw, &ch);
	double y = r.y + (r.height - th - ch - 4) / 2;

	/* The right side: the address and when it was seen */
	const char *when = p->online ? "online" : NULL;
	char *age = NULL;
	if (when == NULL) {
		age = ts_age(p->last_seen);
		when = age[0] ? age : "offline";
	}
	double right = r.x + r.width - pad, rw = 0, rh;
	const char *ip4 = ts_shown_ip(p->ip4);
	if (ip4) {
		c8ui_text_size(family, small, ip4, 0, 1, &rw, &rh);
		c8ui_set_source(cr, item->fg, item->secondary);
		c8ui_text_draw(cr, family, small, ip4, right - rw, y + 2, 0, 1);
	}
	double ww;
	c8ui_text_size(family, small, when, 0, 1, &ww, &rh);
	c8ui_set_source(cr, item->fg, item->secondary);
	c8ui_text_draw(cr, family, small, when, right - ww, y + th + 4, 0, 1);
	double width = right - fmax(rw, ww) - 16 - x;

	c8ui_set_source(cr, item->fg, p->online ? 1 : 0.7);
	char *name = g_strdup_printf("%s%s", ts_shown_name(p), p->exit_node ?
		" · exit node" : "");
	c8ui_text_draw(cr, family, title, name, x, y, width, 1);
	const char *owner = ts_shown_owner(p->owner);
	char *line = g_strdup_printf("%s%s%s", owner ? owner : "",
		owner && p->os ? " · " : "", p->os ? p->os : "");
	c8ui_set_source(cr, item->fg, item->secondary);
	c8ui_text_draw(cr, family, small, line, x, y + th + 4, width, 1);
	g_free(name);
	g_free(line);
	g_free(age);
}

static void show_device(const char *id) {
	g_free(g.device_id);
	g.device_id = g_strdup(id);
	if (c8ui_pages_get(g.pages) != PAGE_DEVICES || !c8ui_pages_showing(g.pages)) {
		c8ui_pages_open(g.pages, PAGE_DEVICES);
	}
	rebuild(true);
}

static void device_opened(struct c8ui_widget *list, int index, void *data) {
	if (index >= 0 && index < (int)g.items->len) {
		struct ts_peer *p = g.items->pdata[index];
		show_device(p->id);
	}
}

static void filter_changed(struct c8ui_widget *entry, void *data) {
	g_free(g.filter);
	g.filter = g_strdup(c8ui_entry_get(entry));
	fill_items();
}

static void devices_page(struct c8ui_widget *box) {
	if (ts.state != TS_RUNNING && ts.state != TS_STOPPED) {
		c8ui_widget_add(box, caption("Log in and connect to see your devices."));
		return;
	}
	struct c8ui_widget *search = c8ui_entry_new(NULL, g.filter ? g.filter : "",
		NULL, NULL);
	c8ui_entry_set_placeholder(search, "Find a device");
	c8ui_entry_set_search(search, true);
	c8ui_entry_on_change(search, filter_changed, NULL);
	search->max_width = 400;
	search->fill = true; // up to its max_width
	c8ui_widget_add(box, search);

	g.list = c8ui_list_new(C8UI_LIST_ROWS, 0, ROW_H, draw_device, NULL);
	c8ui_list_set_click_opens(g.list, true);
	c8ui_list_on_open(g.list, device_opened, NULL);
	g.list->fill = true;
	g.list->max_width = 760;
	c8ui_widget_add(box, g.list);
	fill_items();
	if (g.items->len == 0) {
		c8ui_widget_add(box, caption(g.filter && g.filter[0] ?
			"Nothing matches." : "No other devices on this tailnet yet."));
	}
}

/* One device */

/* From a device to the devices; narrow, from a page to the list */
static void go_back(struct c8ui_widget *w, void *data) {
	c8ui_pages_back(g.pages);
}

static void ping_done(bool ok, const char *out, void *data) {
	if (g.ping_out == NULL) {
		return;
	}
	/* "pong from NAME (IP) via ADDRESS:PORT in 23ms" */
	char *text = g_strstrip(ts_shown_text(out));
	c8ui_label_set_text(g.ping_out, text[0] ? text : ok ? "No answer" :
		"Couldn't ping it");
	c8ui_widget_set_hidden(g.ping_out, false);
	c8ui_ring_set_active(g.ping_ring, false);
	c8ui_widget_set_hidden(g.ping_ring, true);
	g_free(text);
}

static void ping_clicked(struct c8ui_widget *w, void *data) {
	struct ts_peer *p = ts_peer_find(g.device_id);
	if (p == NULL || g.ping_out == NULL) {
		return;
	}
	const char *target = p->ip4 ? p->ip4 : p->dns ? p->dns : p->name;
	const char *argv[] = { "tailscale", "ping", "-c", "3", target, NULL };
	c8ui_label_set_text(g.ping_out, "");
	c8ui_widget_set_hidden(g.ping_out, true);
	c8ui_widget_set_hidden(g.ping_ring, false);
	c8ui_ring_set_active(g.ping_ring, true);
	if (!ts_run(argv, ping_done, NULL)) {
		ping_done(false, "Couldn't run tailscale", NULL);
	}
}

static void send_done(bool ok, const char *out, void *data) {
	char *name = data;
	if (ok) {
		char *say = g_strdup_printf("%s has it.", ts_shown_dns(name));
		show_message("File sent", say);
		g_free(say);
	} else {
		char *say = ts_shown_text(out);
		show_message("Couldn't send the file", say[0] ? say :
			"Tailscale gave no reason.");
		g_free(say);
	}
	g_free(name);
}

static void send_chosen(char **uris, void *data) {
	char *target = data;
	if (uris == NULL || uris[0] == NULL) {
		g_free(target);
		return;
	}
	/* Sending is talking to the peer, which anyone may do */
	GPtrArray *argv = g_ptr_array_new_with_free_func(g_free);
	g_ptr_array_add(argv, g_strdup("tailscale"));
	g_ptr_array_add(argv, g_strdup("file"));
	g_ptr_array_add(argv, g_strdup("cp"));
	g_ptr_array_add(argv, g_strdup("--update-interval=0s"));
	for (int i = 0; uris[i]; i++) {
		char *path = g_filename_from_uri(uris[i], NULL, NULL);
		if (path) {
			g_ptr_array_add(argv, path);
		}
	}
	g_ptr_array_add(argv, g_strdup_printf("%s:", target));
	g_ptr_array_add(argv, NULL);
	if (!ts_run((const char *const *)argv->pdata, send_done, target)) {
		show_message("Couldn't send the file", "Couldn't run tailscale.");
		g_free(target);
	}
	g_ptr_array_unref(argv);
}

static void send_clicked(struct c8ui_widget *w, void *data) {
	struct ts_peer *p = ts_peer_find(g.device_id);
	if (p == NULL || g.win == NULL) {
		return;
	}
	char *title = g_strdup_printf("Send to %s", ts_shown_name(p));
	struct c8ui_file_options opts = {
		.title = title, .accept = "Send", .multiple = true,
	};
	if (c8ui_file_open(g.win, &opts, send_chosen, g_strdup(p->dns ? p->dns :
			p->name)) == NULL) {
		show_message("Couldn't choose a file", "There is no file picker.");
	}
	g_free(title);
}

static void use_exit_clicked(struct c8ui_widget *w, void *data) {
	struct ts_peer *p = ts_peer_find(g.device_id);
	if (p == NULL) {
		return;
	}
	if (p->exit_node) {
		ts_set("exit-node", "", command_done, "Couldn't change the exit node");
	} else {
		ts_set("exit-node", p->ip4 ? p->ip4 : p->name, command_done,
			"Couldn't change the exit node");
	}
}

static void update_bar(void);

/* The rows that change while the page shows */
static char *connection_text(const struct ts_peer *p) {
	if (p->cur_addr && p->cur_addr[0]) {
		return g_strdup_printf("Direct, %s", ts_shown_endpoint(p->cur_addr));
	}
	if (p->active && p->relay && p->relay[0]) {
		return g_strdup_printf("Through the %s relay", p->relay);
	}
	return g_strdup(p->online ? "Idle" : "None");
}

static char *traffic_text(const struct ts_peer *p) {
	char *rx = ts_bytes(p->rx), *tx = ts_bytes(p->tx);
	char *s = g_strdup_printf("%s received, %s sent", rx, tx);
	g_free(rx);
	g_free(tx);
	return s;
}

static void device_page(struct c8ui_widget *box) {
	struct ts_peer *p = ts_peer_find(g.device_id);
	if (p == NULL) {
		c8ui_widget_add(box, caption("That device isn't on the tailnet any "
			"more."));
		c8ui_widget_add(box, c8ui_button_new("Back to the devices", go_back,
			NULL));
		return;
	}
	struct c8ui_widget *grid = details_new();
	char *age = ts_age(p->last_seen);
	detail(grid, "Status", p->online ? "Online" : age[0] ? keepf("Offline, "
		"last seen %s", age) : "Offline", NULL);
	g_free(age);
	detail(grid, "Owner", ts_shown_owner(p->owner), NULL);
	detail(grid, "Hostname", g_strcmp0(p->host, p->name) ?
		ts_shown_host(p) : NULL, NULL);
	detail(grid, "Tags", keep(ts_shown_text(p->tags)), NULL);
	detail(grid, "System", p->os, NULL);
	detail(grid, "MagicDNS name", ts_shown_dns(p->dns), p->dns);
	detail(grid, "IPv4 address", ts_shown_ip(p->ip4), p->ip4);
	detail(grid, "IPv6 address", ts_shown_ip(p->ip6), p->ip6);
	char *how = connection_text(p);
	g.connection = detail(grid, "Connection", how, NULL);
	g_free(how);
	char *traffic = traffic_text(p);
	g.traffic = detail(grid, "Traffic", traffic, NULL);
	g_free(traffic);
	detail(grid, "Exit node", p->exit_node ? "In use by this device" :
		p->exit_option ? "Offers to be one" : NULL, NULL);
	c8ui_widget_add(box, grid);

	struct c8ui_widget *row = c8ui_box_new(C8UI_HORIZONTAL, 12);
	c8ui_box_set_wrap(row, true);
	struct c8ui_widget *ping = c8ui_button_new("Ping", ping_clicked, NULL);
	c8ui_widget_set_disabled(ping, !p->online);
	c8ui_widget_add(row, ping);
	struct c8ui_widget *send = c8ui_button_new("Send a file", send_clicked,
		NULL);
	c8ui_widget_set_disabled(send, !p->online);
	c8ui_widget_add(row, send);
	if (p->exit_option || p->exit_node) {
		c8ui_widget_add(row, c8ui_button_new(p->exit_node ?
			"Stop using as exit node" : "Use as exit node", use_exit_clicked,
			NULL));
	}
	c8ui_widget_add(box, row);

	struct c8ui_widget *out = c8ui_box_new(C8UI_HORIZONTAL, 12);
	g.ping_ring = c8ui_ring_new(0);
	c8ui_ring_set_active(g.ping_ring, false);
	c8ui_widget_set_hidden(g.ping_ring, true);
	c8ui_widget_add(out, g.ping_ring);
	g.ping_out = caption("");
	c8ui_label_set_max_lines(g.ping_out, 6);
	g.ping_out->fill = true;
	c8ui_widget_set_hidden(g.ping_out, true);
	c8ui_widget_add(out, g.ping_out);
	c8ui_widget_add(box, out);
}

/* Exit node */

static void exit_set(const char *what) {
	ts_set("exit-node", what, command_done, "Couldn't change the exit node");
}

static void exit_none(struct c8ui_widget *w, void *data) {
	exit_set("");
}

static void exit_use(struct c8ui_widget *w, void *data) {
	exit_set(data);
}

static void lan_toggled(struct c8ui_widget *w, void *data) {
	ts_set_bool("exit-node-allow-lan-access", c8ui_toggle_get(w), command_done,
		"Couldn't change that");
}

static void advertise_toggled(struct c8ui_widget *w, void *data) {
	ts_set_bool("advertise-exit-node", c8ui_toggle_get(w), command_done,
		"Couldn't change that");
}

static void suggest_done(bool ok, const char *out, void *data) {
	/* "Suggested exit node: us-sea-wg-001.mullvad.ts.net." */
	const char *colon = ok ? strchr(out, ':') : NULL;
	if (colon == NULL) {
		show_message("No suggestion", out[0] ? out : "Tailscale had none.");
		return;
	}
	char *name = g_strstrip(g_strdup(colon + 1));
	char *nl = strchr(name, '\n');
	if (nl) {
		*nl = '\0';
	}
	size_t n = strlen(name);
	if (n && name[n - 1] == '.') {
		name[n - 1] = '\0';
	}
	exit_set(name);
	g_free(name);
}

static void suggest_clicked(struct c8ui_widget *w, void *data) {
	const char *argv[] = { "tailscale", "exit-node", "suggest", NULL };
	ts_run(argv, suggest_done, NULL);
}

/* A row for one exit node to pick: a dot when it's the one in use */
static struct c8ui_widget *exit_row(const char *label, const char *sub,
		bool current, bool online, c8ui_action_fn fn, void *data) {
	struct c8ui_widget *row = c8ui_box_new(C8UI_HORIZONTAL, 14);
	row->fill = true;
	struct c8ui_widget *b = c8ui_button_new(current ? "In use" : "Use", fn,
		data);
	c8ui_button_set_primary(b, current);
	c8ui_widget_set_disabled(b, current || !online);
	b->fixed_width = 90;
	c8ui_widget_add(row, b);
	struct c8ui_widget *text = c8ui_box_new(C8UI_VERTICAL, 2);
	text->expand = true;
	c8ui_widget_add(text, c8ui_label_new(label, C8UI_TEXT_BODY_STRONG));
	if (sub) {
		c8ui_widget_add(text, caption(sub));
	}
	c8ui_widget_add(row, text);
	return row;
}

static int str_cmp(gconstpointer a, gconstpointer b) {
	return g_strcmp0(*(const char *const *)a, *(const char *const *)b);
}

static void add_unique(GPtrArray *list, const char *s) {
	for (guint i = 0; s && i < list->len; i++) {
		if (strcmp(list->pdata[i], s) == 0) {
			return;
		}
	}
	if (s) {
		g_ptr_array_add(list, g_strdup(s));
	}
}

static void fill_cities(void) {
	g_ptr_array_set_size(g.cities, 0);
	const char *country = g.mullvad_country >= 0 &&
		g.mullvad_country < (int)g.countries->len ?
		g.countries->pdata[g.mullvad_country] : NULL;
	for (guint i = 0; country && ts.peers && i < ts.peers->len; i++) {
		struct ts_peer *p = ts.peers->pdata[i];
		if (p->mullvad && p->online && g_strcmp0(p->country, country) == 0) {
			add_unique(g.cities, p->city ? p->city : p->name);
		}
	}
	g_ptr_array_sort(g.cities, str_cmp);
}

static void country_changed(struct c8ui_widget *w, void *data) {
	g.mullvad_country = c8ui_combo_get(w);
	fill_cities();
	g_ptr_array_add(g.cities, NULL);
	c8ui_combo_set_items(g.city, (const char *const *)g.cities->pdata,
		g.cities->len - 1, 0);
	g_ptr_array_remove_index(g.cities, g.cities->len - 1);
}

/* The Mullvad node for the country and city chosen: the first online */
static void mullvad_use(struct c8ui_widget *w, void *data) {
	const char *country = g.mullvad_country >= 0 &&
		g.mullvad_country < (int)g.countries->len ?
		g.countries->pdata[g.mullvad_country] : NULL;
	int ci = g.city ? c8ui_combo_get(g.city) : -1;
	const char *city = ci >= 0 && ci < (int)g.cities->len ?
		g.cities->pdata[ci] : NULL;
	for (guint i = 0; country && ts.peers && i < ts.peers->len; i++) {
		struct ts_peer *p = ts.peers->pdata[i];
		if (p->mullvad && p->online && g_strcmp0(p->country, country) == 0 &&
				(city == NULL || g_strcmp0(p->city ? p->city : p->name,
				city) == 0)) {
			exit_set(p->ip4 ? p->ip4 : p->name);
			return;
		}
	}
	show_message("No exit node there", "None is online in that place right "
		"now.");
}

static void exit_page(struct c8ui_widget *box) {
	if (ts.state != TS_RUNNING) {
		c8ui_widget_add(box, caption("Connect to pick an exit node."));
		return;
	}
	c8ui_widget_add(box, caption("An exit node carries all of this device's "
		"internet traffic, as a VPN does."));
	struct ts_peer *current = ts_exit_node();

	struct c8ui_widget *list = c8ui_box_new(C8UI_VERTICAL, 10);
	list->fill = true;
	c8ui_widget_add(list, exit_row("None", "Traffic goes straight out",
		current == NULL, true, exit_none, NULL));
	bool any = false;
	for (guint i = 0; ts.peers && i < ts.peers->len; i++) {
		struct ts_peer *p = ts.peers->pdata[i];
		if (p->mullvad || !p->exit_option) {
			continue;
		}
		any = true;
		const char *sub = p->online ? (p->owner ? keepf("%s · online",
			ts_shown_owner(p->owner)) : "online") : "offline";
		c8ui_widget_add(list, exit_row(ts_shown_name(p), sub, p == current, p->online,
			exit_use, (void *)keep(g_strdup(p->ip4 ? p->ip4 : p->name))));
	}
	if (current && current->mullvad) {
		c8ui_widget_add(list, exit_row(keepf("Mullvad, %s", current->city ?
			current->city : current->name), current->country, true, true,
			exit_none, NULL));
	}
	c8ui_widget_add(box, list);
	if (!any && !ts.can_mullvad) {
		c8ui_widget_add(box, caption("No device on your tailnet offers to be "
			"an exit node. Turn one on with \"Offer this device as an exit "
			"node\" below, on the device that should be one."));
	}

	if (ts.can_mullvad) {
		c8ui_widget_add(box, section_title("Mullvad"));
		c8ui_widget_add(box, caption("Your tailnet includes Mullvad's exit "
			"nodes around the world."));
		g_ptr_array_set_size(g.countries, 0);
		for (guint i = 0; ts.peers && i < ts.peers->len; i++) {
			struct ts_peer *p = ts.peers->pdata[i];
			if (p->mullvad && p->online) {
				add_unique(g.countries, p->country ? p->country : "Unknown");
			}
		}
		g_ptr_array_sort(g.countries, str_cmp);
		if (g.mullvad_country < 0 || g.mullvad_country >= (int)g.countries->len) {
			g.mullvad_country = 0;
		}
		fill_cities();
		struct c8ui_widget *row = c8ui_box_new(C8UI_HORIZONTAL, 16);
		c8ui_box_set_wrap(row, true);
		g_ptr_array_add(g.countries, NULL);
		g.country = c8ui_combo_new("Country",
			(const char *const *)g.countries->pdata, g.countries->len - 1,
			g.mullvad_country, country_changed, NULL);
		g_ptr_array_remove_index(g.countries, g.countries->len - 1);
		g.country->fixed_width = 240;
		c8ui_widget_add(row, g.country);
		g_ptr_array_add(g.cities, NULL);
		g.city = c8ui_combo_new("City", (const char *const *)g.cities->pdata,
			g.cities->len - 1, 0, NULL, NULL);
		g_ptr_array_remove_index(g.cities, g.cities->len - 1);
		g.city->fixed_width = 240;
		c8ui_widget_add(row, g.city);
		c8ui_widget_add(box, row);
		struct c8ui_widget *buttons = c8ui_box_new(C8UI_HORIZONTAL, 12);
		c8ui_widget_add(buttons, c8ui_button_new("Use this one", mullvad_use,
			NULL));
		c8ui_widget_add(buttons, c8ui_button_new("Pick the nearest",
			suggest_clicked, NULL));
		c8ui_widget_add(box, buttons);
	} else if (any) {
		c8ui_widget_add(box, c8ui_button_new("Pick the nearest",
			suggest_clicked, NULL));
	}

	c8ui_widget_add(box, section_title("Options"));
	c8ui_widget_add(box, c8ui_toggle_new("Allow access to the local network",
		"Printers and shares nearby stay reachable while an exit node is in "
		"use", ts.allow_lan, lan_toggled, NULL));
	c8ui_widget_add(box, c8ui_toggle_new("Offer this device as an exit node",
		"Other devices on the tailnet may send their traffic through it; an "
		"admin has to approve it", ts.advertise_exit, advertise_toggled,
		NULL));
}

/* Account */

static void logout_chosen(int choice, void *data) {
	if (choice == 0) {
		const char *args[] = { "logout", NULL };
		ts_control(args, command_done, "Couldn't log out");
	}
}

static void logout_clicked(struct c8ui_widget *w, void *data) {
	static const char *const buttons[] = { "Log out", "Cancel" };
	c8ui_dialog_show(g.root, "Log out of Tailscale?", "This device leaves the "
		"tailnet until you log in again, and its key expires.", buttons, 2,
		logout_chosen, NULL);
}

static void add_account_clicked(struct c8ui_widget *w, void *data) {
	/* A login while logged in starts a new profile beside this one */
	login_clicked(w, data);
}

static void switch_clicked(struct c8ui_widget *w, void *data) {
	const char *args[] = { "switch", data, NULL };
	ts_control(args, command_done, "Couldn't switch accounts");
}

static void accounts_fill(void) {
	if (g.accounts_box == NULL) {
		return;
	}
	c8ui_widget_clear(g.accounts_box);
	int others = 0;
	for (guint i = 0; g.accounts && i < g.accounts->len; i++) {
		struct ts_account *a = g.accounts->pdata[i];
		if (a->selected || a->id == NULL) {
			continue;
		}
		others++;
		const char *tailnet = ts_shown_tailnet(a->tailnet);
		const char *account = ts_shown_login(a->account);
		const char *label = tailnet && account ? keepf("%s (%s)", tailnet,
			account) : tailnet ? tailnet : account ? account : a->id;
		struct c8ui_widget *row = c8ui_box_new(C8UI_HORIZONTAL, 14);
		struct c8ui_widget *b = c8ui_button_new("Switch", switch_clicked,
			(void *)keep(g_strdup(a->id)));
		b->fixed_width = 90;
		c8ui_widget_add(row, b);
		struct c8ui_widget *l = c8ui_label_new(label, C8UI_TEXT_BODY);
		l->expand = true;
		c8ui_widget_add(row, l);
		c8ui_widget_add(g.accounts_box, row);
	}
	if (others == 0) {
		c8ui_widget_add(g.accounts_box, caption("No other account is logged in "
			"on this device."));
	}
}

static void accounts_read(GPtrArray *accounts, void *data) {
	ts_accounts_free(g.accounts);
	g.accounts = accounts;
	accounts_fill();
}

static void account_page(struct c8ui_widget *box) {
	if (ts.state == TS_NEEDS_LOGIN || ts.state == TS_NO_DAEMON ||
			ts.state == TS_NOT_INSTALLED) {
		c8ui_widget_add(box, caption("Log in first, on the Status page."));
		return;
	}
	struct c8ui_widget *grid = details_new();
	const char *name = ts_shown_owner(ts.user_name);
	const char *login = ts_shown_login(ts.user_login);
	detail(grid, "Logged in as", name && login && strcmp(name, login) ?
		keepf("%s (%s)", name, login) : login ? login : name, NULL);
	detail(grid, "Tailnet", ts_shown_tailnet(ts.tailnet), NULL);
	detail(grid, "MagicDNS suffix", ts_shown_suffix(ts.magic_dns), NULL);
	c8ui_widget_add(box, grid);
	struct c8ui_widget *row = c8ui_box_new(C8UI_HORIZONTAL, 12);
	c8ui_box_set_wrap(row, true);
	c8ui_widget_add(row, c8ui_button_new("Open the admin console", open_link,
		(void *)ADMIN_URL));
	c8ui_widget_add(row, c8ui_button_new("Log out", logout_clicked, NULL));
	c8ui_widget_add(box, row);

	c8ui_widget_add(box, section_title("Other accounts"));
	c8ui_widget_add(box, caption("This device can be logged in to several "
		"tailnets and be on one at a time."));
	g.accounts_box = c8ui_box_new(C8UI_VERTICAL, 10);
	g.accounts_box->fill = true;
	c8ui_widget_add(box, g.accounts_box);
	if (g.accounts) {
		accounts_fill();
	}
	ts_accounts(accounts_read, NULL);
	c8ui_widget_add(box, c8ui_button_new("Add an account", add_account_clicked,
		NULL));
}

/* The content */

/* Forgets the page's widgets. A page destroyed during an event is freed
 * after it, so its on_destroy comes once the next page is built: it must
 * not touch the new one (content_gone checks it is still the current). */
static void forget_page(void) {
	g.content = NULL;
	g.list = g.connection = g.traffic = g.ping_out = g.ping_ring = NULL;
	g.country = g.city = g.accounts_box = NULL;
	if (g.strings) {
		g_ptr_array_set_size(g.strings, 0);
	}
}

static void content_gone(struct c8ui_widget *w, void *data) {
	if (w == g.content) {
		forget_page();
	}
}

/* What the page is built from: a change in it builds the page again,
 * one in the rest (traffic, who's idle) doesn't */
static char *fingerprint(void) {
	GString *s = g_string_new(NULL);
	g_string_append_printf(s, "%d|%s|%s|%s|%s|%s|%s|%s|%s|%s|%d%d%d%d%d%d%d|%s|%s|"
		"%d|%s|%s|%d\n", ts.state, ts.error ? ts.error : "",
		ts.auth_url ? ts.auth_url : "", ts.self_name ? ts.self_name : "",
		ts.self_dns ? ts.self_dns : "", ts.self_ip4 ? ts.self_ip4 : "",
		ts.self_ip6 ? ts.self_ip6 : "", ts.tailnet ? ts.tailnet : "",
		ts.user_login ? ts.user_login : "", ts.user_name ? ts.user_name : "",
		ts.accept_routes, ts.accept_dns, ts.allow_lan, ts.ssh, ts.shields_up,
		ts.advertise_exit, ts.is_operator, ts.hostname ? ts.hostname : "",
		ts.exit_node_id ? ts.exit_node_id : "", ts.exit_node_online,
		ts.version ? ts.version : "", g.device_id ? g.device_id : "",
		ts_login_pending());
	for (int i = 0; ts.health && ts.health[i]; i++) {
		g_string_append_printf(s, "%s\n", ts.health[i]);
	}
	for (guint i = 0; ts.peers && i < ts.peers->len; i++) {
		struct ts_peer *p = ts.peers->pdata[i];
		g_string_append_printf(s, "%s %s %s %d%d%d %s\n", p->id ? p->id : "",
			p->name, p->ip4 ? p->ip4 : "", p->online, p->exit_node,
			p->exit_option, p->owner ? p->owner : "");
	}
	return g_string_free(s, FALSE);
}

/* A device's page lies over Devices, under its name */
static void sync_sub(void) {
	struct ts_peer *p = g.device_id ? ts_peer_find(g.device_id) : NULL;
	c8ui_pages_set_sub(g.pages, g.device_id == NULL ? NULL : p ?
		ts_shown_name(p) : "Device");
}

static void build_page(struct c8ui_widget *pages, struct c8ui_widget *content,
		void *data) {
	forget_page();
	g.page = c8ui_pages_get(pages);
	if (g.page != PAGE_DEVICES) {
		/* Another page was picked from the list */
		g_clear_pointer(&g.device_id, g_free);
	}
	g.content = content;
	content->on_destroy = content_gone;
	content->max_width = 760;
	if (g.device_id) {
		device_page(content);
	} else {
		switch (g.page) {
		case PAGE_STATUS: status_page(content); break;
		case PAGE_DEVICES: devices_page(content); break;
		case PAGE_EXIT: exit_page(content); break;
		case PAGE_ACCOUNT: account_page(content); break;
		default: break;
		}
	}
	/* What it was built from, so only a change in that builds it again */
	g_free(g.fingerprint);
	g.fingerprint = fingerprint();
	update_bar();
}

/* Back from a device's page: Devices is built again by the pages */
static void device_left(struct c8ui_widget *pages, void *data) {
	g_clear_pointer(&g.device_id, g_free);
}

static void update_bar(void) {
	if (g.appbar == NULL) {
		return;
	}
	bool device = g.page == PAGE_DEVICES && g.device_id &&
		ts_peer_find(g.device_id);
	struct ts_peer *p = device ? ts_peer_find(g.device_id) : NULL;
	c8ui_widget_set_hidden(g.cmd_copy, !device || p->ip4 == NULL);
	c8ui_widget_set_hidden(g.cmd_ping, !device || !p->online);
	c8ui_widget_set_hidden(g.cmd_send, !device || !p->online);
	c8ui_widget_set_hidden(g.cmd_exit, !device || !(p->exit_option ||
		p->exit_node));
	c8ui_widget_set_hidden(g.cmd_files, ts.state != TS_RUNNING);
}

/* force: the page itself changed; otherwise only when what it shows did.
 * Returns whether it was built again. */
static bool rebuild(bool force) {
	if (g.pages == NULL) {
		return false;
	}
	char *now = fingerprint();
	bool changed = g.fingerprint == NULL || strcmp(now, g.fingerprint) != 0;
	g_free(now);
	if (force || changed) {
		sync_sub();
		c8ui_pages_rebuild(g.pages, force);
	} else {
		/* A fresh read gives fresh peers: the list's rows point at them */
		fill_items();
		struct ts_peer *p = ts_peer_find(g.device_id);
		if (p && g.connection) {
			char *t = connection_text(p);
			c8ui_label_set_text(g.connection, t);
			g_free(t);
		}
		if (p && g.traffic) {
			char *t = traffic_text(p);
			c8ui_label_set_text(g.traffic, t);
			g_free(t);
		}
		update_bar();
	}
	return force || changed;
}

/* App bar */

static void cmd_refresh(struct c8ui_widget *w, void *data) {
	ts_refresh();
}

static void cmd_copy(struct c8ui_widget *w, void *data) {
	struct ts_peer *p = ts_peer_find(g.device_id);
	if (p && p->ip4) {
		copy_text(NULL, p->ip4);
	}
}

static bool keys(const struct c8ui_event *ev, void *data) {
	if (ev->sym == XKB_KEY_Escape && c8ui_pages_back(g.pages)) {
		return true;
	}
	if (ev->sym == XKB_KEY_Menu) {
		update_bar();
		c8ui_appbar_toggle(g.appbar);
		return true;
	}
	if (ev->sym == XKB_KEY_F5 || ((ev->mods & C8UI_MOD_CTRL) &&
			ev->base_sym == XKB_KEY_r)) {
		ts_refresh();
		return true;
	}
	return false;
}

/* Changes */

static void status_changed(void *data) {
	apply_theme();
	/* A login was asked for: go where it says as soon as it says */
	if (g.open_auth && ts.auth_url) {
		g.open_auth = false;
		open_link(NULL, ts.auth_url);
	}
	int poll = ts.state == TS_NEEDS_LOGIN || ts_login_pending() ||
		ts.state == TS_STARTING ? POLL_LOGIN_S : POLL_S;
	if (poll != g.poll_s) {
		g.poll_s = poll;
		ts_poll(poll);
	}
	/* The flyout is built again only when something it shows changed, or
	 * typing a name in it would be undone every few seconds */
	if (rebuild(false) && g.charms) {
		c8ui_charms_changed(g.charms, "options");
	}
	tile_later();
}

/* Stealth mode on or off, or another persona: everything drawn again */
static void stealth_changed(void *data) {
	if (g.pages) {
		sync_sub();
		c8ui_pages_rebuild(g.pages, true);
	}
	if (g.list) {
		c8ui_list_redraw(g.list);
	}
	if (g.charms) {
		c8ui_charms_changed(g.charms, "options");
	}
	tile_later();
}

/* Charms */

static void search(struct c8ui_search *s, const char *query, void *data) {
	if (query[0] == '\0') {
		return;
	}
	char *q = g_utf8_casefold(query, -1);
	int found = 0;
	for (guint i = 0; ts.peers && i < ts.peers->len && found < 20; i++) {
		struct ts_peer *p = ts.peers->pdata[i];
		if (p->mullvad || !peer_matches(p, q) || p->id == NULL) {
			continue;
		}
		char *age = ts_age(p->last_seen);
		char *sub = g_strdup_printf("%s · %s", p->ip4 ? ts_shown_ip(p->ip4) :
			"", p->online ? "online" : age[0] ? age : "offline");
		c8ui_search_add(s, p->id, ts_shown_name(p), sub, NULL);
		g_free(sub);
		g_free(age);
		found++;
	}
	g_free(q);
}

static void open_result(const char *id, const char *query, void *data) {
	if (g.win && ts_peer_find(id)) {
		show_device(id);
	}
}

static void option_changed(struct c8ui_setting *s, void *data) {
	const char *id = c8ui_setting_id(s);
	if (strcmp(id, "hostname") == 0) {
		/* Enter on the stand-in stealth mode shows isn't a new name */
		if (c8_stealth() && ts.hostname &&
				strcmp(c8ui_setting_get_text(s), ts_shown_self()) == 0) {
			return;
		}
		ts_set("hostname", c8ui_setting_get_text(s), command_done,
			"Couldn't rename this device");
	} else if (strcmp(id, "refresh") == 0) {
		ts_refresh();
	} else {
		/* The id is the flag */
		ts_set_bool(id, c8ui_setting_get_bool(s), command_done,
			"Couldn't change that");
	}
}

static void options_page(struct c8ui_settings_page *page, void *data) {
	if (ts.state == TS_NOT_INSTALLED || ts.state == TS_NO_DAEMON) {
		c8ui_page_paragraph(page, "Tailscale isn't running.");
		return;
	}
	c8ui_page_heading(page, "Network");
	struct c8ui_setting *s;
	s = c8ui_page_toggle(page, "accept-routes", "Use subnet routes",
		ts.accept_routes, option_changed, NULL);
	c8ui_setting_set_description(s, "Reach the networks other devices on the "
		"tailnet share");
	s = c8ui_page_toggle(page, "accept-dns", "Use Tailscale DNS",
		ts.accept_dns, option_changed, NULL);
	c8ui_setting_set_description(s, "MagicDNS names and the tailnet's DNS "
		"settings");
	s = c8ui_page_toggle(page, "exit-node-allow-lan-access",
		"Allow access to the local network", ts.allow_lan, option_changed,
		NULL);
	c8ui_setting_set_description(s, "While an exit node is in use");
	c8ui_page_heading(page, "This device");
	s = c8ui_page_toggle(page, "shields-up", "Block incoming connections",
		ts.shields_up, option_changed, NULL);
	c8ui_setting_set_description(s, "Other devices can't reach this one");
	s = c8ui_page_toggle(page, "ssh", "Tailscale SSH", ts.ssh, option_changed,
		NULL);
	c8ui_setting_set_description(s, "Let the tailnet's policy decide who may "
		"log in over SSH");
	s = c8ui_page_toggle(page, "advertise-exit-node",
		"Offer this device as an exit node", ts.advertise_exit, option_changed,
		NULL);
	s = c8ui_page_text(page, "hostname", "Name on the tailnet",
		ts.hostname ? (c8_stealth() ? ts_shown_self() : ts.hostname) : "",
		option_changed, NULL);
	c8ui_setting_set_placeholder(s, ts.self_name ? ts_shown_self() : "");
	c8ui_page_button(page, "refresh", "Refresh now", option_changed, NULL);
}

/* The app */

static void window_gone(struct c8ui_widget *w, void *data) {
	g.win = NULL;
	g.root = NULL;
	g.pages = g.content = g.appbar = NULL;
	g.list = g.connection = g.traffic = g.ping_out = g.ping_ring = NULL;
	g.country = g.city = g.accounts_box = NULL;
	g_clear_pointer(&g.fingerprint, g_free);
	g_clear_pointer(&g.device_id, g_free);
	if (g.strings) {
		g_ptr_array_unref(g.strings);
		g.strings = NULL;
	}
	if (g.items) {
		g_ptr_array_unref(g.items);
		g.items = NULL;
	}
	ts_poll(0);
	g.poll_s = 0;
}

/* The pane is the Start background colour, as PC settings' is; the theme
 * may change while the app runs, so this is done again now and then */
static void apply_theme(void) {
	if (g.pages && g.app) {
		c8ui_widget_set_background(c8ui_pages_pane(g.pages),
			c8ui_app_theme(g.app)->background);
	}
}

static struct c8ui_widget *command(const char *icon, const char *label,
		bool right, c8ui_action_fn fn) {
	return c8ui_appbar_add(g.appbar, icon, label, right, fn, NULL);
}

static void make_window(void) {
	g.win = c8ui_window_new(g.app, "Tailscale", 1100, 720);
	g.root = c8ui_window_root(g.win);
	g.strings = g_ptr_array_new_with_free_func(g_free);
	g.items = g_ptr_array_new();

	g.pages = c8ui_pages_new("Tailscale", PANE_WIDTH, build_page, NULL);
	g.pages->on_destroy = window_gone;
	for (int i = 0; i < PAGE_COUNT; i++) {
		c8ui_pages_add(g.pages, page_titles[i]);
	}
	c8ui_pages_on_back(g.pages, device_left, NULL);
	apply_theme();
	c8ui_root_set_child(g.root, g.pages);
	c8ui_root_set_key_handler(g.root, keys, NULL);

	g.appbar = c8ui_appbar_new(g.root);
	g.cmd_copy = command("edit-copy", "Copy address", false, cmd_copy);
	g.cmd_ping = command("network-transmit-receive", "Ping", false,
		ping_clicked);
	g.cmd_send = command("document-send", "Send a file", false, send_clicked);
	g.cmd_exit = command("network-vpn", "Exit node", false, use_exit_clicked);
	g.cmd_files = command("folder-download", "Received files", true,
		collect_files);
	g.cmd_refresh = command("view-refresh", "Refresh", true, cmd_refresh);

	g.mullvad_country = -1;
	/* One asked for by name shows even if the window is narrow */
	if (g.page_given) {
		c8ui_pages_open(g.pages, g.page);
	}
}

static void startup(struct c8ui_app *app, void *data) {
	g.app = app;
	g.countries = g_ptr_array_new_with_free_func(g_free);
	g.cities = g_ptr_array_new_with_free_func(g_free);
	g.charms = c8ui_charms_new(app);
	if (g.charms) {
		c8ui_charms_on_search(g.charms, search, open_result, NULL, NULL);
		c8ui_charms_add_page(g.charms, "options", "Options", options_page,
			NULL);
	}
	ts_on_change(status_changed, NULL);
	c8_stealth_watch(stealth_changed, NULL);
}

static void open(struct c8ui_app *app, char **uris, void *data) {
	if (g.win == NULL) {
		make_window();
		ts_refresh();
	}
	c8ui_window_present(g.win);
}

static void shutdown(struct c8ui_app *app, void *data) {
	if (g.tile_timer) {
		g_source_remove(g.tile_timer);
		tile_now(NULL);
	}
	c8ui_charms_destroy(g.charms);
}

static const char *const page_args[PAGE_COUNT] = {
	"status", "devices", "exit-node", "account",
};

int main(int argc, char **argv) {
	/* --page NAME opens on that page (the rest is c8ui_app_main's) */
	for (int i = 1; i + 1 < argc; i++) {
		if (strcmp(argv[i], "--page") == 0) {
			for (int p = 0; p < PAGE_COUNT; p++) {
				if (strcmp(argv[i + 1], page_args[p]) == 0) {
					g.page = p;
					g.page_given = true; // narrow: on the page, not the list
				}
			}
			memmove(&argv[i], &argv[i + 2], (argc - i - 1) * sizeof(*argv));
			argc -= 2;
			break;
		}
	}
	static const struct c8ui_app_info info = {
		.id = APP_ID,
		.startup = startup,
		.open = open,
		.shutdown = shutdown,
	};
	return c8ui_app_main(&info, argc, argv);
}
