/*
 * The PC settings app and the private protocol it uses.
 *
 * The compositor starts c8-settings itself, over a socket pair, and only
 * that connection can see the c8_settings_manager_v1 global: no other
 * client can read or change the configuration through it. But for
 * c8-sync, started the same way, which carries the settings to and from
 * the online account.
 */
#define _GNU_SOURCE
#include <fcntl.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/inotify.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <unistd.h>
#include <wlr/types/wlr_compositor.h>
#include <wlr/types/wlr_security_context_v1.h>
#include <wlr/util/log.h>
#include "cont8nuum-settings-v1-protocol.h"
#include "server.h"
#include "stealth.h"

#define SETTINGS_PROGRAM "c8-settings"
#define SYNC_PROGRAM "c8-sync"
#define SYNC_RESPAWN_MS 30000
#define SYNC_TRIES 5
#define WATCH_MS 200 // editors write in steps: wait for the last

struct c8_settings_handle {
	struct wl_list link; // c8_server.settings_handles
	struct wl_resource *resource;
	struct c8_server *server;
	struct c8_config_op *ops;
	int op_count, op_cap;
};

/* Snapshot */

static void entry(struct wl_resource *r, const char *section, const char *key,
		const char *value) {
	c8_settings_v1_send_entry(r, section, key, value ? value : "");
}

static void entry_bool(struct wl_resource *r, const char *section,
		const char *key, bool value) {
	entry(r, section, key, value ? "true" : "false");
}

static void entry_fmt(struct wl_resource *r, const char *section,
		const char *key, const char *fmt, ...) {
	char buf[128];
	va_list ap;
	va_start(ap, fmt);
	vsnprintf(buf, sizeof(buf), fmt, ap);
	va_end(ap);
	entry(r, section, key, buf);
}

static void send_snapshot(struct c8_server *server, struct wl_resource *r) {
	struct c8_config *c = &server->config;

	entry(r, "general", "terminal", c->terminal);
	entry(r, "general", "font", c->font);
	entry(r, "general", "icon_theme", c->icon_theme);
	entry(r, "general", "cursor_theme", c->cursor_theme);
	entry_fmt(r, "general", "cursor_size", "%d", c->cursor_size);
	entry_bool(r, "general", "xwayland", c->xwayland);
	entry(r, "general", "clock", c->clock);
	entry(r, "notifications", "corner", c->notify_corner);
	for (int i = 0; i < c->autostart_len; i++) {
		entry(r, "general", "autostart", c->autostart[i]);
	}

	entry(r, "keyboard", "layout", c->xkb_layout);
	entry(r, "keyboard", "variant", c->xkb_variant);
	entry(r, "keyboard", "options", c->xkb_options);
	entry_fmt(r, "keyboard", "repeat_rate", "%d", c->repeat_rate);
	entry_fmt(r, "keyboard", "repeat_delay", "%d", c->repeat_delay);

	entry_bool(r, "touchpad", "tap", c->touchpad.tap);
	entry_bool(r, "touchpad", "natural_scroll", c->touchpad.natural_scroll);
	entry_bool(r, "touchpad", "disable_while_typing",
		c->touchpad.disable_while_typing);
	entry_fmt(r, "touchpad", "speed", "%.2f", c->touchpad.speed);
	entry_bool(r, "mouse", "natural_scroll", c->mouse.natural_scroll);
	entry_bool(r, "mouse", "left_handed", c->mouse.left_handed);
	entry_fmt(r, "mouse", "speed", "%.2f", c->mouse.speed);

	entry(r, "power", "lock", c->lock_cmd);
	entry(r, "power", "sleep", c->sleep_cmd);
	entry(r, "power", "restart", c->restart_cmd);
	entry(r, "power", "shutdown", c->shutdown_cmd);

	entry(r, "display", "project", c8_project_name(c->project));
	entry_bool(r, "nightlight", "enabled", c->night.enabled);
	entry_fmt(r, "nightlight", "temperature", "%d", c->night.temperature);
	entry(r, "nightlight", "schedule",
		c8_night_schedule_name(c->night.schedule));
	entry_fmt(r, "nightlight", "from", "%02d:%02d", c->night.from / 60,
		c->night.from % 60);
	entry_fmt(r, "nightlight", "to", "%02d:%02d", c->night.to / 60,
		c->night.to % 60);
	if (c->night.has_place) {
		entry_fmt(r, "nightlight", "place", "%g, %g", c->night.latitude,
			c->night.longitude);
	} else {
		entry(r, "nightlight", "place", "");
	}
	entry_bool(r, "glasses", "outlines", c->glasses.outlines);
	entry(r, "glasses", "background", c->glasses.background);
	entry_fmt(r, "glasses", "background_horizon", "%g",
		c->glasses.background_horizon);
	entry_bool(r, "glasses", "steady", c->glasses.steady);
	entry_bool(r, "glasses", "sbs_switch", c->glasses.sbs_switch);
	entry(r, "glasses", "runtime",
		c->glasses.runtime == C8_XR_RUNTIME_MONADO ? "monado" :
		c->glasses.runtime == C8_XR_RUNTIME_BUILTIN ? "builtin" : "auto");
	entry_fmt(r, "glasses", "fov", "%g", c->glasses.fov);
	entry_fmt(r, "glasses", "distance", "%g", c->glasses.distance);
	entry_fmt(r, "glasses", "start_distance", "%g",
		c->glasses.start_distance);
	entry_fmt(r, "glasses", "ipd", "%g", c->glasses.ipd);
	entry_fmt(r, "glasses", "screen", "%dx%d", c->glasses.screen_w,
		c->glasses.screen_h);
	entry_fmt(r, "glasses", "latency", "%d", c->glasses.latency);
	if (c->glasses.scanout < 0) {
		entry(r, "glasses", "scanout", "auto");
	} else {
		entry_fmt(r, "glasses", "scanout", "%g", c->glasses.scanout);
	}
	entry_fmt(r, "glasses", "tilt", "%g", c->glasses.tilt);
	entry_fmt(r, "glasses", "neck", "%g %g", c->glasses.neck_up,
		c->glasses.neck_ahead);

	struct c8_binding *b;
	wl_list_for_each(b, &c->bindings, link) {
		char combo[128], command[1024];
		c8_format_combo(b->modifiers, b->sym, combo, sizeof(combo));
		snprintf(command, sizeof(command), "%s%s%s", c8_action_name(b->action),
			b->arg ? " " : "", b->arg ? b->arg : "");
		entry(r, "bindings", combo, command);
	}

	entry_fmt(r, "appearance", "accent", "#%06x", c->accent & 0xffffff);
	entry_fmt(r, "appearance", "background", "#%06x", c->background & 0xffffff);
	entry(r, "appearance", "pattern", c8_pattern_name(c->pattern));
	entry_bool(r, "appearance", "more_tiles", c->more_tiles);
	entry_bool(r, "appearance", "live_tiles", c->live_tiles);
	for (int i = 0; i < c8_palette_len; i++) {
		entry_fmt(r, "palette", "accent", "#%06x", c8_palette[i]);
	}
	for (int i = 0; i < c8_backgrounds_len; i++) {
		entry_fmt(r, "palette", "background", "#%06x", c8_backgrounds[i]);
	}
	for (int i = 0; i < C8_PATTERN_COUNT; i++) {
		entry(r, "palette", "pattern", c8_pattern_name(i));
	}

	struct c8_output_config *oc;
	wl_list_for_each(oc, &c->outputs, link) {
		char section[300];
		snprintf(section, sizeof(section), "output %s", oc->name);
		if (oc->enabled >= 0) {
			entry_bool(r, section, "enabled", oc->enabled);
		}
		if (oc->has_mode) {
			if (oc->refresh) {
				entry_fmt(r, section, "mode", "%dx%d@%.3f", oc->width,
					oc->height, oc->refresh / 1000.0);
			} else {
				entry_fmt(r, section, "mode", "%dx%d", oc->width, oc->height);
			}
		}
		if (oc->has_pos) {
			entry_fmt(r, section, "position", "%d,%d", oc->x, oc->y);
		}
		if (oc->scale > 0) {
			entry_fmt(r, section, "scale", "%g", oc->scale);
		}
		if (oc->transform >= 0) {
			entry(r, section, "transform", c8_transform_name(oc->transform));
		}
	}
	c8_settings_v1_send_done(r);
}

static void broadcast(struct c8_server *server) {
	struct c8_settings_handle *h;
	wl_list_for_each(h, &server->settings_handles, link) {
		send_snapshot(server, h->resource);
	}
}

/* Applying */

static bool str_changed(const char *a, const char *b) {
	return strcmp(a ? a : "", b ? b : "") != 0;
}

/* Make the running session match a freshly loaded config.ini */
static void apply_reload(struct c8_server *server, struct c8_config *old) {
	struct c8_config *c = &server->config;
	if (str_changed(old->xkb_layout, c->xkb_layout) ||
			str_changed(old->xkb_variant, c->xkb_variant) ||
			str_changed(old->xkb_options, c->xkb_options) ||
			old->repeat_rate != c->repeat_rate ||
			old->repeat_delay != c->repeat_delay) {
		c8_input_configure_keyboards(server);
	}
	c8_input_configure_pointers(server);
	if (str_changed(old->cursor_theme, c->cursor_theme) ||
			old->cursor_size != c->cursor_size) {
		c8_cursor_theme_changed(server);
	}
	if (str_changed(old->icon_theme, c->icon_theme)) {
		c8ui_icon_cache_reset();
	}
	if (str_changed(old->icon_theme, c->icon_theme) ||
			str_changed(old->font, c->font) ||
			old->accent != c->accent || old->background != c->background ||
			old->pattern != c->pattern || old->more_tiles != c->more_tiles ||
			old->live_tiles != c->live_tiles ||
			str_changed(old->notify_corner, c->notify_corner) ||
			str_changed(old->clock, c->clock)) {
		c8_shell_appearance_changed(server);
	}
	if (old->accent != c->accent) {
		c8_views_arrange(server); // the focused app's border
	}
	if (str_changed(old->lock_cmd, c->lock_cmd) ||
			str_changed(old->sleep_cmd, c->sleep_cmd) ||
			str_changed(old->restart_cmd, c->restart_cmd) ||
			str_changed(old->shutdown_cmd, c->shutdown_cmd)) {
		c8_shell_power_changed(server);
	}
	if (old->night.enabled != c->night.enabled ||
			old->night.temperature != c->night.temperature ||
			old->night.schedule != c->night.schedule ||
			old->night.from != c->night.from ||
			old->night.to != c->night.to ||
			old->night.has_place != c->night.has_place ||
			old->night.latitude != c->night.latitude ||
			old->night.longitude != c->night.longitude) {
		c8_nightlight_configure(server);
	}
	c8_output_apply_config(server); // XR too: [glasses] runtime
	c8_idle_configure(server);
	if (c8_stealth_reload()) { // [stealth], read by c8-base
		c8_views_stealth_changed(server);
	}
}

/* Why an [appearance] value can't be used, or NULL */
static const char *check_appearance(const char *key, const char *value) {
	uint32_t rgb;
	if (strcmp(key, "accent") == 0 || strcmp(key, "background") == 0) {
		return c8ui_parse_color(value, &rgb) ? NULL : "Not a colour";
	}
	if (strcmp(key, "pattern") == 0) {
		for (int i = 0; i < C8_PATTERN_COUNT; i++) {
			if (strcmp(value, c8_pattern_name(i)) == 0) {
				return NULL;
			}
		}
		return "Not a pattern";
	}
	if (strcmp(key, "more_tiles") == 0 || strcmp(key, "live_tiles") == 0) {
		return strcmp(value, "true") == 0 || strcmp(value, "false") == 0 ?
			NULL : "Not true or false";
	}
	return "Not a setting that can be changed";
}

/*
 * config.ini edited by hand applies at once, as PC settings' changes do.
 * Our own writes come back here too: the text is kept so they, and
 * saves that change nothing, are let be.
 */
static struct {
	struct wl_event_source *source, *timer;
	char *text; // config.ini as last applied
} watch;

static char *config_text(struct c8_server *server) {
	char path[4096];
	snprintf(path, sizeof(path), "%s/config.ini", server->config.dir);
	FILE *f = fopen(path, "r");
	if (f == NULL) {
		return strdup("");
	}
	char *text = NULL;
	size_t len = 0;
	FILE *out = open_memstream(&text, &len);
	char buf[4096];
	size_t n;
	while ((n = fread(buf, 1, sizeof(buf), f)) > 0) {
		fwrite(buf, 1, n, out);
	}
	fclose(f);
	fclose(out);
	return text;
}

/* Saves the edits to config.ini and makes the session match */
static bool apply_ops(struct c8_server *server, const struct c8_config_op *ops,
		int count) {
	if (!c8_config_patch(server, ops, count)) {
		return false;
	}
	struct c8_config old;
	c8_config_reload(server, &old);
	apply_reload(server, &old);
	c8_config_free_file(&old);
	if (watch.timer) {
		free(watch.text);
		watch.text = config_text(server);
	}
	return true;
}

/* What can't be saved is better refused now than ignored at next login */
static const char *check_op(const struct c8_config_op *op) {
	if (strcmp(op->section, "palette") == 0) {
		return "Read-only";
	}
	if (strcmp(op->section, "appearance") == 0) {
		if (op->type == C8_CONFIG_REMOVE || op->value == NULL) {
			return "Not a setting that can be removed";
		}
		return check_appearance(op->key, op->value);
	}
	if (strcmp(op->section, "general") == 0 &&
			strcmp(op->key, "cursor_size") == 0 && op->value) {
		char *end;
		long size = strtol(op->value, &end, 10);
		if (*end || size < C8_CURSOR_MIN || size > C8_CURSOR_MAX) {
			return "Not a pointer size";
		}
	}
	if (strcmp(op->section, "general") == 0 &&
			strcmp(op->key, "clock") == 0 && op->value &&
			strcmp(op->value, "auto") != 0 && strcmp(op->value, "12") != 0 &&
			strcmp(op->value, "24") != 0) {
		return "Not a clock: auto, 12 or 24";
	}
	if (strcmp(op->section, "notifications") == 0 &&
			strcmp(op->key, "corner") == 0 && op->value) {
		static const char *const corners[] = { "top-right", "top-left",
			"bottom-right", "bottom-left" };
		bool ok = false;
		for (int i = 0; i < 4; i++) {
			ok |= strcmp(op->value, corners[i]) == 0;
		}
		if (!ok) {
			return "Not a corner";
		}
	}
	if (strcmp(op->section, "nightlight") == 0 && op->value) {
		enum c8_night_schedule schedule;
		int minutes;
		double lat, lon;
		if (strcmp(op->key, "temperature") == 0 &&
				(atoi(op->value) < C8_NIGHT_MIN_K ||
				atoi(op->value) > C8_NIGHT_MAX_K)) {
			return "Not a colour temperature: 1500 to 6000";
		}
		if (strcmp(op->key, "schedule") == 0 &&
				!c8_night_schedule_parse(op->value, &schedule)) {
			return "Not a schedule: times, sunset or always";
		}
		if ((strcmp(op->key, "from") == 0 || strcmp(op->key, "to") == 0) &&
				!c8_parse_time(op->value, &minutes)) {
			return "Not a time of day, as 21:00";
		}
		if (strcmp(op->key, "place") == 0 && op->value[0] &&
				(sscanf(op->value, "%lf , %lf", &lat, &lon) != 2 ||
				fabs(lat) > 90 || fabs(lon) > 180)) {
			return "Not a place, as 47.6, -122.3";
		}
	}
	if (strcmp(op->section, "display") == 0 &&
			strcmp(op->key, "project") == 0 && op->value) {
		enum c8_project p;
		if (!c8_project_parse(op->value, &p)) {
			return "Not a choice: auto, pc, duplicate, second or "
				"xr";
		}
	}
	if (strcmp(op->section, "bindings") == 0 && op->key[0] &&
			op->type != C8_CONFIG_REMOVE) {
		uint32_t mods;
		xkb_keysym_t sym;
		if (!c8_parse_combo(op->key, &mods, &sym)) {
			return "Not a key combination";
		}
		char action[32];
		snprintf(action, sizeof(action), "%.*s",
			(int)strcspn(op->value, " \t"), op->value);
		bool known = strcmp(action, "none") == 0;
		for (int a = C8_ACTION_EXEC; a < C8_ACTION_COUNT && !known; a++) {
			known = strcmp(c8_action_name(a), action) == 0;
		}
		if (!known) {
			return "Unknown action";
		}
	}
	return NULL;
}

static void handle_commit(struct wl_client *client, struct wl_resource *resource) {
	struct c8_settings_handle *h = wl_resource_get_user_data(resource);
	struct c8_server *server = h->server;
	struct c8_config_op *file_ops = calloc(h->op_count + 1, sizeof(*file_ops));
	int file_count = 0;
	/* A replaced list of bindings is all or nothing: saved without a
	 * refused line, the built-in key it shadowed would be bound to none */
	bool replaces = false, refused = false;
	for (int i = 0; i < h->op_count; i++) {
		struct c8_config_op *op = &h->ops[i];
		if (strcmp(op->section, "bindings") != 0) {
			continue;
		}
		replaces |= op->type == C8_CONFIG_REMOVE && op->key[0] == '\0';
		refused |= check_op(op) != NULL;
	}
	bool keep_bindings = replaces && refused;
	for (int i = 0; i < h->op_count; i++) {
		struct c8_config_op *op = &h->ops[i];
		const char *why = check_op(op);
		if (why) {
			c8_settings_v1_send_failed(resource, op->section, op->key, why);
			continue;
		}
		if (keep_bindings && strcmp(op->section, "bindings") == 0) {
			continue;
		}
		file_ops[file_count++] = *op;
	}
	if (keep_bindings) {
		c8_settings_v1_send_failed(resource, "bindings", "",
			"Your shortcuts weren't changed");
	}
	if (file_count > 0) {
		if (!apply_ops(server, file_ops, file_count)) {
			c8_settings_v1_send_failed(resource, "", "",
				"Could not save config.ini");
		}
	}
	free(file_ops);
	for (int i = 0; i < h->op_count; i++) {
		free(h->ops[i].section);
		free(h->ops[i].key);
		free(h->ops[i].value);
	}
	h->op_count = 0;
	broadcast(server);
}

/* Requests */

static void push_op(struct wl_resource *resource, enum c8_config_op_type type,
		const char *section, const char *key, const char *value) {
	struct c8_settings_handle *h = wl_resource_get_user_data(resource);
	if (h->op_count == h->op_cap) {
		h->op_cap = h->op_cap ? h->op_cap * 2 : 16;
		h->ops = realloc(h->ops, sizeof(*h->ops) * h->op_cap);
	}
	h->ops[h->op_count++] = (struct c8_config_op){
		.type = type,
		.section = strdup(section),
		.key = strdup(key),
		.value = value ? strdup(value) : NULL,
	};
}

static void handle_set(struct wl_client *client, struct wl_resource *resource,
		const char *section, const char *key, const char *value) {
	push_op(resource, C8_CONFIG_SET, section, key, value);
}

static void handle_add(struct wl_client *client, struct wl_resource *resource,
		const char *section, const char *key, const char *value) {
	push_op(resource, C8_CONFIG_ADD, section, key, value);
}

static void handle_remove(struct wl_client *client, struct wl_resource *resource,
		const char *section, const char *key) {
	push_op(resource, C8_CONFIG_REMOVE, section, key, NULL);
}

static void handle_destroy(struct wl_client *client, struct wl_resource *resource) {
	wl_resource_destroy(resource);
}

static const struct c8_settings_v1_interface settings_impl = {
	.destroy = handle_destroy,
	.set = handle_set,
	.add = handle_add,
	.remove = handle_remove,
	.commit = handle_commit,
};

static void settings_resource_destroy(struct wl_resource *resource) {
	struct c8_settings_handle *h = wl_resource_get_user_data(resource);
	for (int i = 0; i < h->op_count; i++) {
		free(h->ops[i].section);
		free(h->ops[i].key);
		free(h->ops[i].value);
	}
	free(h->ops);
	wl_list_remove(&h->link);
	free(h);
}

static void manager_get_settings(struct wl_client *client,
		struct wl_resource *resource, uint32_t id) {
	struct c8_server *server = wl_resource_get_user_data(resource);
	struct wl_resource *r = wl_resource_create(client, &c8_settings_v1_interface,
		wl_resource_get_version(resource), id);
	if (r == NULL) {
		wl_client_post_no_memory(client);
		return;
	}
	struct c8_settings_handle *h = calloc(1, sizeof(*h));
	h->resource = r;
	h->server = server;
	wl_list_insert(&server->settings_handles, &h->link);
	wl_resource_set_implementation(r, &settings_impl, h,
		settings_resource_destroy);
	send_snapshot(server, r);
}

static void manager_destroy(struct wl_client *client,
		struct wl_resource *resource) {
	wl_resource_destroy(resource);
}

static const struct c8_settings_manager_v1_interface manager_impl = {
	.destroy = manager_destroy,
	.get_settings = manager_get_settings,
};

static void manager_bind(struct wl_client *client, void *data, uint32_t version,
		uint32_t id) {
	struct c8_server *server = data;
	/* The global filter already hides it; this is belt and braces */
	if (client != server->settings_client && client != server->sync_client) {
		wl_client_post_implementation_error(client,
			"c8_settings_manager_v1 is only for the settings app");
		return;
	}
	struct wl_resource *resource = wl_resource_create(client,
		&c8_settings_manager_v1_interface, version, id);
	if (resource == NULL) {
		wl_client_post_no_memory(client);
		return;
	}
	wl_resource_set_implementation(resource, &manager_impl, server, NULL);
}

/* What a sandboxed app (one that came in through a security context,
 * as Flatpak's do) isn't shown: with these it could type and click for
 * you, read every key, the screen and the clipboard, or draw over
 * everything, and the sandbox would hold nothing in. Screen sharing
 * still reaches it through the portal, which asks. */
static bool sandbox_hidden(const struct wl_global *global) {
	static const char *const names[] = {
		"zwp_virtual_keyboard_manager_v1",
		"zwlr_virtual_pointer_manager_v1",
		"zwp_input_method_manager_v2",
		"ext_data_control_manager_v1",
		"zwlr_data_control_manager_v1",
		"zwlr_screencopy_manager_v1",
		"zwlr_export_dmabuf_manager_v1",
		"ext_image_copy_capture_manager_v1",
		"ext_output_image_capture_source_manager_v1",
		"ext_foreign_toplevel_image_capture_source_manager_v1",
		"ext_foreign_toplevel_list_v1",
		"zwlr_foreign_toplevel_manager_v1",
		"zwlr_layer_shell_v1",
		"zwlr_output_manager_v1",
		"zwlr_gamma_control_manager_v1",
		"ext_session_lock_manager_v1",
		"wp_security_context_manager_v1",
		"wp_drm_lease_device_v1",
	};
	const char *name = wl_global_get_interface(global)->name;
	for (size_t i = 0; i < sizeof(names) / sizeof(names[0]); i++) {
		if (strcmp(names[i], name) == 0) {
			return true;
		}
	}
	return false;
}

static bool global_filter(const struct wl_client *client,
		const struct wl_global *global, void *data) {
	struct c8_server *server = data;
	if (server->security_context &&
			wlr_security_context_manager_v1_lookup_client(
				server->security_context, client) &&
			sandbox_hidden(global)) {
		return false;
	}
	if (global == server->settings_global) {
		return client == server->settings_client ||
			client == server->sync_client;
	}
	if (global == server->shell.global) {
		return c8_shell_is_client(server, client);
	}
	if (server->lock.manager && global == server->lock.manager->global) {
		return c8_lock_is_client(server, client);
	}
	if (!c8_lease_global_visible(server, client, global)) {
		return false;
	}
	return c8_output_global_visible(server, client, global);
}

/* Launching */

static void settings_client_destroy(struct wl_listener *listener, void *data) {
	struct c8_server *server =
		wl_container_of(listener, server, settings_client_destroy);
	wl_list_remove(&server->settings_client_destroy.link);
	server->settings_client = NULL;
}

static struct c8_view *settings_view(struct c8_server *server) {
	struct c8_view *view;
	wl_list_for_each(view, &server->views, link) {
		struct wlr_surface *surface = view->impl->get_surface(view);
		if (view->mapped && surface &&
				wl_resource_get_client(surface->resource) ==
				server->settings_client) {
			return view;
		}
	}
	return NULL;
}

bool c8_settings_is_launch(const char *cmd) {
	if (strcmp(cmd, "@pc-settings") == 0) {
		return true;
	}
	size_t n = strcspn(cmd, " \t");
	const char *slash = memrchr(cmd, '/', n);
	const char *name = slash ? slash + 1 : cmd;
	return n - (name - cmd) == strlen(SETTINGS_PROGRAM) &&
		strncmp(name, SETTINGS_PROGRAM, strlen(SETTINGS_PROGRAM)) == 0;
}

void c8_settings_launch(struct c8_server *server, const char *cmd) {
	if (server->settings_client) {
		struct c8_view *view = settings_view(server);
		if (view) {
			c8_view_activate(view);
		}
		return;
	}

	/* The arguments after the program, split on blanks; no shell, so
	 * nothing but c8-settings ever runs on this connection */
	char *argv[16] = { SETTINGS_PROGRAM };
	int argc = 1;
	char *copy = strdup(cmd);
	char *save = NULL;
	char *tok = strtok_r(copy, " \t", &save); // the program itself
	while (tok && argc < 15 && (tok = strtok_r(NULL, " \t", &save))) {
		argv[argc++] = tok;
	}
	if (strcmp(cmd, "@pc-settings") == 0) {
		argc = 1;
	}
	argv[argc] = NULL;

	struct wl_client *client = c8_spawn_client(server, argv);
	free(copy);
	if (client == NULL) {
		return;
	}
	server->settings_client = client;
	server->settings_client_destroy.notify = settings_client_destroy;
	wl_client_add_destroy_listener(client, &server->settings_client_destroy);
}

/* c8-sync */

static void sync_client_destroy(struct wl_listener *listener, void *data) {
	struct c8_server *server =
		wl_container_of(listener, server, sync_client_destroy);
	wl_list_remove(&server->sync_client_destroy.link);
	server->sync_client = NULL;
	/* It runs for the whole session: gone means it fell over, or isn't
	 * installed. A few more tries, then the session does without. */
	if (server->sync_respawn && server->sync_tries < SYNC_TRIES) {
		wl_event_source_timer_update(server->sync_respawn, SYNC_RESPAWN_MS);
	}
}

static int sync_spawn(void *data) {
	struct c8_server *server = data;
	if (server->sync_client) {
		return 0;
	}
	server->sync_tries++;
	char *argv[] = { SYNC_PROGRAM, NULL };
	struct wl_client *client = c8_spawn_client(server, argv);
	if (client == NULL) {
		return 0;
	}
	server->sync_client = client;
	server->sync_client_destroy.notify = sync_client_destroy;
	wl_client_add_destroy_listener(client, &server->sync_client_destroy);
	return 0;
}

void c8_sync_start(struct c8_server *server) {
	/* Nested there is no session of ours to keep in step; C8_SYNC is
	 * for trying it there */
	if (server->session == NULL && getenv("C8_SYNC") == NULL) {
		return;
	}
	server->sync_respawn = wl_event_loop_add_timer(server->loop, sync_spawn,
		server);
	sync_spawn(server);
}

static int watch_settled(void *data) {
	struct c8_server *server = data;
	char *text = config_text(server);
	if (watch.text && strcmp(text, watch.text) == 0) {
		free(text);
		return 0;
	}
	free(watch.text);
	watch.text = text;
	wlr_log(WLR_INFO, "config.ini changed: applying it");
	struct c8_config old;
	c8_config_reload(server, &old);
	apply_reload(server, &old);
	c8_config_free_file(&old);
	broadcast(server);
	return 0;
}

static int watch_read(int fd, uint32_t mask, void *data) {
	char buf[4096] __attribute__((aligned(__alignof__(struct inotify_event))));
	ssize_t len;
	bool ours = false;
	while ((len = read(fd, buf, sizeof(buf))) > 0) {
		for (char *p = buf; p < buf + len;) {
			struct inotify_event *ev = (struct inotify_event *)p;
			if (ev->len && strcmp(ev->name, "config.ini") == 0) {
				ours = true;
			}
			p += sizeof(*ev) + ev->len;
		}
	}
	if (ours) {
		wl_event_source_timer_update(watch.timer, WATCH_MS);
	}
	return 0;
}

static void watch_config(struct c8_server *server) {
	int fd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
	if (fd < 0) {
		return;
	}
	/* The folder, not the file: editors save by renaming a new one in */
	if (inotify_add_watch(fd, server->config.dir,
			IN_CLOSE_WRITE | IN_MOVED_TO | IN_CREATE) < 0) {
		wlr_log_errno(WLR_ERROR, "Can't watch %s", server->config.dir);
		close(fd);
		return;
	}
	watch.text = config_text(server);
	watch.timer = wl_event_loop_add_timer(server->loop, watch_settled,
		server);
	watch.source = wl_event_loop_add_fd(server->loop, fd,
		WL_EVENT_READABLE, watch_read, server);
}

void c8_settings_init(struct c8_server *server) {
	wl_list_init(&server->settings_handles);
	server->settings_global = wl_global_create(server->display,
		&c8_settings_manager_v1_interface, 1, server, manager_bind);
	server->security_context =
		wlr_security_context_manager_v1_create(server->display);
	wl_display_set_global_filter(server->display, global_filter, server);
	watch_config(server);
}

bool c8_settings_set_appearance(struct c8_server *server, const char *key,
		const char *value) {
	if (check_appearance(key, value)) {
		return false;
	}
	struct c8_config_op op = {
		.type = C8_CONFIG_SET,
		.section = "appearance",
		.key = (char *)key,
		.value = (char *)value,
	};
	if (!apply_ops(server, &op, 1)) {
		return false;
	}
	broadcast(server);
	return true;
}

bool c8_settings_set(struct c8_server *server, const char *section,
		const char *key, const char *value) {
	struct c8_config_op op = {
		.type = C8_CONFIG_SET,
		.section = (char *)section,
		.key = (char *)key,
		.value = (char *)value,
	};
	const char *why = check_op(&op);
	if (why) {
		wlr_log(WLR_ERROR, "[%s] %s = %s: %s", section, key, value, why);
		return false;
	}
	if (!apply_ops(server, &op, 1)) {
		return false;
	}
	broadcast(server);
	return true;
}
