#define _GNU_SOURCE
#include <ctype.h>
#include <math.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <sys/stat.h>
#include <wlr/types/wlr_keyboard.h>
#include <wlr/util/log.h>
#include "server.h"

static const char *pattern_names[] = {
	[C8_PATTERN_NONE] = "none",
	[C8_PATTERN_CIRCLES] = "circles",
	[C8_PATTERN_LINES] = "lines",
	[C8_PATTERN_SQUARES] = "squares",
};

const char *c8_pattern_name(enum c8_pattern pattern) {
	return pattern_names[pattern];
}

static int mkdir_p(const char *path) {
	char buf[1024];
	snprintf(buf, sizeof(buf), "%s", path);
	for (char *p = buf + 1; *p; p++) {
		if (*p == '/') {
			*p = '\0';
			mkdir(buf, 0755);
			*p = '/';
		}
	}
	if (mkdir(buf, 0755) != 0 && errno != EEXIST) {
		return -1;
	}
	return 0;
}

static bool parse_bool(const char *s) {
	return strcmp(s, "true") == 0 || strcmp(s, "yes") == 0 ||
		strcmp(s, "on") == 0 || strcmp(s, "1") == 0;
}

static const char *const night_schedules[] = { "times", "sunset", "always" };

const char *c8_night_schedule_name(enum c8_night_schedule schedule) {
	return night_schedules[schedule];
}

bool c8_night_schedule_parse(const char *s, enum c8_night_schedule *out) {
	for (int i = 0; i < 3; i++) {
		if (strcmp(s, night_schedules[i]) == 0) {
			*out = i;
			return true;
		}
	}
	return false;
}

/* "21:30" as minutes into the day */
bool c8_parse_time(const char *s, int *minutes) {
	int h, m;
	char end;
	if (sscanf(s, "%d:%d%c", &h, &m, &end) != 2 || h < 0 || h > 23 ||
			m < 0 || m > 59) {
		return false;
	}
	*minutes = h * 60 + m;
	return true;
}

static char *trim(char *s) {
	while (isspace((unsigned char)*s)) {
		s++;
	}
	char *end = s + strlen(s);
	while (end > s && isspace((unsigned char)end[-1])) {
		*--end = '\0';
	}
	return s;
}

bool c8_ini_parse(void *data, const char *path, c8_ini_handler handler) {
	FILE *f = fopen(path, "r");
	if (f == NULL) {
		return false;
	}
	char section[256] = "";
	char *line = NULL;
	size_t cap = 0;
	int lineno = 0;
	while (getline(&line, &cap, f) > 0) {
		lineno++;
		char *s = trim(line);
		if (s[0] == '\0' || s[0] == '#' || s[0] == ';') {
			continue;
		}
		if (s[0] == '[') {
			char *end = strchr(s, ']');
			if (end == NULL) {
				wlr_log(WLR_ERROR, "%s:%d: unterminated section", path, lineno);
				continue;
			}
			*end = '\0';
			snprintf(section, sizeof(section), "%s", trim(s + 1));
			handler(data, section, NULL, NULL);
			continue;
		}
		/* Split on the first " = " style separator, so keys like
		 * "Super+Shift+equal" in [bindings] still work. */
		char *eq = strchr(s, '=');
		if (eq == NULL) {
			wlr_log(WLR_ERROR, "%s:%d: expected key = value", path, lineno);
			continue;
		}
		*eq = '\0';
		handler(data, section, trim(s), trim(eq + 1));
	}
	free(line);
	fclose(f);
	return true;
}

static const struct {
	const char *name;
	enum c8_action_type action;
} action_names[] = {
	{ "exec", C8_ACTION_EXEC },
	{ "start", C8_ACTION_START },
	{ "search", C8_ACTION_SEARCH },
	{ "close", C8_ACTION_CLOSE },
	{ "snap-left", C8_ACTION_SNAP_LEFT },
	{ "snap-right", C8_ACTION_SNAP_RIGHT },
	{ "unsnap", C8_ACTION_UNSNAP },
	{ "split-left", C8_ACTION_SPLIT_LEFT },
	{ "split-right", C8_ACTION_SPLIT_RIGHT },
	{ "switcher", C8_ACTION_SWITCHER },
	{ "app-windows", C8_ACTION_APP_WINDOWS },
	{ "charms", C8_ACTION_CHARMS },
	{ "settings", C8_ACTION_SETTINGS },
	{ "pc-settings", C8_ACTION_PC_SETTINGS },
	{ "apps", C8_ACTION_APPS },
	{ "quit", C8_ACTION_QUIT },
	{ "screenshot", C8_ACTION_SCREENSHOT },
	{ "screenshot-window", C8_ACTION_SCREENSHOT_WINDOW },
	{ "screenshot-save", C8_ACTION_SCREENSHOT_SAVE },
	{ "snip", C8_ACTION_SNIP },
	{ "project", C8_ACTION_PROJECT },
	{ "glasses-recentre", C8_ACTION_GLASSES_RECENTRE },
	{ "night-light", C8_ACTION_NIGHT_LIGHT },
	{ "volume-up", C8_ACTION_VOLUME_UP },
	{ "volume-down", C8_ACTION_VOLUME_DOWN },
	{ "mute", C8_ACTION_MUTE },
	{ "mic-mute", C8_ACTION_MIC_MUTE },
	{ "brightness-up", C8_ACTION_BRIGHTNESS_UP },
	{ "brightness-down", C8_ACTION_BRIGHTNESS_DOWN },
	{ "play-pause", C8_ACTION_PLAY_PAUSE },
	{ "next-track", C8_ACTION_NEXT_TRACK },
	{ "previous-track", C8_ACTION_PREVIOUS_TRACK },
	{ "stop-media", C8_ACTION_STOP_MEDIA },
};

const char *c8_action_name(enum c8_action_type action) {
	for (size_t i = 0; i < sizeof(action_names) / sizeof(action_names[0]); i++) {
		if (action_names[i].action == action) {
			return action_names[i].name;
		}
	}
	return "none";
}

bool c8_parse_combo(const char *combo, uint32_t *mods_out,
		xkb_keysym_t *sym_out) {
	uint32_t mods = 0;
	xkb_keysym_t sym = XKB_KEY_NoSymbol;
	char *copy = strdup(combo);
	char *save = NULL;
	bool ok = true;
	for (char *tok = strtok_r(copy, "+", &save); tok;
			tok = strtok_r(NULL, "+", &save)) {
		tok = trim(tok);
		if (strcasecmp(tok, "Super") == 0 || strcasecmp(tok, "Logo") == 0 ||
				strcasecmp(tok, "Mod4") == 0) {
			mods |= WLR_MODIFIER_LOGO;
		} else if (strcasecmp(tok, "Alt") == 0 || strcasecmp(tok, "Mod1") == 0) {
			mods |= WLR_MODIFIER_ALT;
		} else if (strcasecmp(tok, "Ctrl") == 0 ||
				strcasecmp(tok, "Control") == 0) {
			mods |= WLR_MODIFIER_CTRL;
		} else if (strcasecmp(tok, "Shift") == 0) {
			mods |= WLR_MODIFIER_SHIFT;
		} else if (sym == XKB_KEY_NoSymbol) {
			sym = xkb_keysym_from_name(tok, XKB_KEYSYM_CASE_INSENSITIVE);
			ok = sym != XKB_KEY_NoSymbol;
		} else {
			ok = false; /* two keys */
		}
	}
	free(copy);
	if (!ok || sym == XKB_KEY_NoSymbol) {
		return false;
	}
	*mods_out = mods;
	*sym_out = xkb_keysym_to_lower(sym);
	return true;
}

void c8_format_combo(uint32_t mods, xkb_keysym_t sym, char *buf, size_t len) {
	char name[64];
	if (xkb_keysym_get_name(sym, name, sizeof(name)) < 0) {
		snprintf(name, sizeof(name), "0x%x", sym);
	}
	snprintf(buf, len, "%s%s%s%s%s",
		(mods & WLR_MODIFIER_LOGO) ? "Super+" : "",
		(mods & WLR_MODIFIER_CTRL) ? "Ctrl+" : "",
		(mods & WLR_MODIFIER_ALT) ? "Alt+" : "",
		(mods & WLR_MODIFIER_SHIFT) ? "Shift+" : "", name);
}

static void add_binding(struct c8_config *config, const char *combo,
		const char *command) {
	uint32_t mods;
	xkb_keysym_t sym;
	if (!c8_parse_combo(combo, &mods, &sym)) {
		wlr_log(WLR_ERROR, "Invalid key binding '%s'", combo);
		return;
	}

	char *cmd = strdup(command);
	char *arg = cmd;
	while (*arg && !isspace((unsigned char)*arg)) {
		arg++;
	}
	if (*arg) {
		*arg++ = '\0';
		arg = trim(arg);
	}
	enum c8_action_type action = C8_ACTION_NONE;
	for (size_t i = 0; i < sizeof(action_names) / sizeof(action_names[0]); i++) {
		if (strcmp(cmd, action_names[i].name) == 0) {
			action = action_names[i].action;
		}
	}
	if (action == C8_ACTION_NONE && strcmp(cmd, "none") != 0) {
		wlr_log(WLR_ERROR, "Unknown action '%s' for binding '%s'", cmd, combo);
		free(cmd);
		return;
	}

	/* Later bindings replace earlier ones for the same combo. */
	struct c8_binding *b, *tmp;
	wl_list_for_each_safe(b, tmp, &config->bindings, link) {
		if (b->modifiers == mods && b->sym == sym) {
			wl_list_remove(&b->link);
			free(b->arg);
			free(b);
		}
	}
	if (action != C8_ACTION_NONE) {
		b = calloc(1, sizeof(*b));
		b->modifiers = mods;
		b->sym = sym;
		b->action = action;
		b->arg = *arg ? strdup(arg) : NULL;
		wl_list_insert(config->bindings.prev, &b->link);
	}
	free(cmd);
}

static const char *transform_names[] = {
	"normal", "90", "180", "270",
	"flipped", "flipped-90", "flipped-180", "flipped-270",
};

const char *c8_transform_name(int transform) {
	if (transform < 0 || transform > 7) {
		return "normal";
	}
	return transform_names[transform];
}

struct c8_output_config *c8_output_config_find(struct c8_config *config,
		const char *name) {
	struct c8_output_config *oc;
	wl_list_for_each(oc, &config->outputs, link) {
		if (strcmp(oc->name, name) == 0) {
			return oc;
		}
	}
	return NULL;
}

static struct c8_output_config *output_config_get(struct c8_config *config,
		const char *name) {
	struct c8_output_config *oc = c8_output_config_find(config, name);
	if (oc == NULL) {
		oc = calloc(1, sizeof(*oc));
		oc->name = strdup(name);
		oc->enabled = -1;
		oc->transform = -1;
		wl_list_insert(config->outputs.prev, &oc->link);
	}
	return oc;
}

static void output_handler(struct c8_config *config, const char *name,
		const char *key, const char *value) {
	struct c8_output_config *oc = output_config_get(config, name);
	if (strcmp(key, "enabled") == 0) {
		oc->enabled = parse_bool(value);
	} else if (strcmp(key, "mode") == 0) {
		double hz = 0;
		int n = sscanf(value, "%dx%d@%lf", &oc->width, &oc->height, &hz);
		oc->has_mode = n >= 2 && oc->width > 0 && oc->height > 0;
		oc->refresh = n == 3 ? (int)lround(hz * 1000) : 0;
	} else if (strcmp(key, "position") == 0) {
		oc->has_pos = sscanf(value, "%d,%d", &oc->x, &oc->y) == 2;
	} else if (strcmp(key, "scale") == 0) {
		double scale = strtod(value, NULL);
		oc->scale = scale >= 0.25 && scale <= 8 ? (float)scale : 0;
	} else if (strcmp(key, "transform") == 0) {
		for (int i = 0; i < 8; i++) {
			if (strcmp(value, transform_names[i]) == 0) {
				oc->transform = i;
			}
		}
	}
}

static double parse_speed(const char *value) {
	double v = strtod(value, NULL);
	return v < -1 ? -1 : v > 1 ? 1 : v;
}

/* Personalisation; it was kept in start.ini before the shell moved out */
static void appearance_handler(struct c8_config *config, const char *key,
		const char *value) {
	if (strcmp(key, "accent") == 0) {
		config->has_appearance |= c8ui_parse_color(value, &config->accent);
	} else if (strcmp(key, "background") == 0) {
		config->has_appearance |= c8ui_parse_color(value, &config->background);
	} else if (strcmp(key, "pattern") == 0) {
		for (int i = 0; i < C8_PATTERN_COUNT; i++) {
			if (strcmp(value, pattern_names[i]) == 0) {
				config->pattern = i;
				config->has_appearance = true;
			}
		}
	} else if (strcmp(key, "more_tiles") == 0) {
		config->more_tiles = parse_bool(value);
		config->has_appearance = true;
	} else if (strcmp(key, "live_tiles") == 0) {
		config->live_tiles = parse_bool(value);
		config->has_appearance = true;
	}
}

static void config_handler(void *data, const char *section,
		const char *key, const char *value) {
	struct c8_config *config = data;
	if (key == NULL) {
		return;
	}
	if (strcmp(section, "appearance") == 0) {
		appearance_handler(config, key, value);
		return;
	}
	if (strcmp(section, "general") == 0) {
		if (strcmp(key, "terminal") == 0) {
			c8_set_str(&config->terminal, value);
		} else if (strcmp(key, "font") == 0) {
			c8_set_str(&config->font, value[0] ? value : C8_DEFAULT_FONT);
		} else if (strcmp(key, "icon_theme") == 0) {
			c8_set_str(&config->icon_theme, value[0] ? value : NULL);
		} else if (strcmp(key, "cursor_theme") == 0) {
			c8_set_str(&config->cursor_theme, value[0] ? value : NULL);
		} else if (strcmp(key, "cursor_size") == 0) {
			int size = atoi(value);
			config->cursor_size = size >= C8_CURSOR_MIN && size <= C8_CURSOR_MAX ?
				size : C8_CURSOR_SIZE;
		} else if (strcmp(key, "clock") == 0) {
			c8_set_str(&config->clock, value[0] ? value : "auto");
		} else if (strcmp(key, "xwayland") == 0) {
			config->xwayland = parse_bool(value);
		} else if (strcmp(key, "autostart") == 0) {
			config->autostart = realloc(config->autostart,
				sizeof(char *) * (config->autostart_len + 1));
			config->autostart[config->autostart_len++] = strdup(value);
		}
	} else if (strcmp(section, "notifications") == 0) {
		if (strcmp(key, "corner") == 0) {
			c8_set_str(&config->notify_corner, value);
		}
	} else if (strcmp(section, "keyboard") == 0) {
		if (strcmp(key, "layout") == 0) {
			c8_set_str(&config->xkb_layout, value);
		} else if (strcmp(key, "variant") == 0) {
			c8_set_str(&config->xkb_variant, value);
		} else if (strcmp(key, "options") == 0) {
			c8_set_str(&config->xkb_options, value);
		} else if (strcmp(key, "repeat_rate") == 0) {
			int v = atoi(value);
			config->repeat_rate = v < 0 ? 0 : v > 100 ? 100 : v;
		} else if (strcmp(key, "repeat_delay") == 0) {
			int v = atoi(value);
			config->repeat_delay = v < 100 ? 100 : v > 2000 ? 2000 : v;
		}
	} else if (strcmp(section, "touchpad") == 0) {
		if (strcmp(key, "tap") == 0) {
			config->touchpad.tap = parse_bool(value);
		} else if (strcmp(key, "natural_scroll") == 0) {
			config->touchpad.natural_scroll = parse_bool(value);
		} else if (strcmp(key, "disable_while_typing") == 0) {
			config->touchpad.disable_while_typing = parse_bool(value);
		} else if (strcmp(key, "speed") == 0) {
			config->touchpad.speed = parse_speed(value);
		}
	} else if (strcmp(section, "mouse") == 0) {
		if (strcmp(key, "natural_scroll") == 0) {
			config->mouse.natural_scroll = parse_bool(value);
		} else if (strcmp(key, "left_handed") == 0) {
			config->mouse.left_handed = parse_bool(value);
		} else if (strcmp(key, "speed") == 0) {
			config->mouse.speed = parse_speed(value);
		}
	} else if (strcmp(section, "power") == 0) {
		if (strcmp(key, "lock") == 0) {
			c8_set_str(&config->lock_cmd, value);
		} else if (strcmp(key, "sleep") == 0) {
			c8_set_str(&config->sleep_cmd, value);
		} else if (strcmp(key, "restart") == 0) {
			c8_set_str(&config->restart_cmd, value);
		} else if (strcmp(key, "shutdown") == 0) {
			c8_set_str(&config->shutdown_cmd, value);
		} else if (strcmp(key, "screen_off_after") == 0) {
			config->screen_off_after = atoi(value) > 0 ? atoi(value) : 0;
		} else if (strcmp(key, "sleep_after") == 0) {
			config->sleep_after = atoi(value) > 0 ? atoi(value) : 0;
		} else if (strcmp(key, "locker") == 0) {
			c8_set_str(&config->locker, value);
		} else if (strcmp(key, "lock_when_off") == 0) {
			config->lock_when_off = parse_bool(value);
		}
	} else if (strcmp(section, "glasses") == 0) {
		double v = atof(value);
		if (strcmp(key, "fov") == 0 && v >= 20 && v <= 140) {
			config->glasses.fov = v;
		} else if (strcmp(key, "distance") == 0 && v >= 0.3 && v <= 20) {
			config->glasses.distance = v;
		} else if (strcmp(key, "ipd") == 0 && v >= 45 && v <= 85) {
			config->glasses.ipd = v;
		} else if (strcmp(key, "latency") == 0 && v >= 0 && v <= 100) {
			config->glasses.latency = (int)v;
		} else if (strcmp(key, "scanout") == 0) {
			if (strcmp(value, "auto") == 0) {
				config->glasses.scanout = -1;
			} else if (v >= 0 && v <= 50) {
				config->glasses.scanout = v;
			}
		} else if (strcmp(key, "tilt") == 0 && v >= -90 && v <= 90) {
			config->glasses.tilt = v;
		} else if (strcmp(key, "neck") == 0) {
			double up, ahead;
			if (sscanf(value, "%lf %lf", &up, &ahead) == 2 &&
					fabs(up) <= 0.3 && fabs(ahead) <= 0.3) {
				config->glasses.neck_up = up;
				config->glasses.neck_ahead = ahead;
			}
		} else if (strcmp(key, "outlines") == 0) {
			config->glasses.outlines = parse_bool(value);
		} else if (strcmp(key, "background") == 0) {
			c8_set_str(&config->glasses.background,
				value[0] ? value : NULL);
		} else if (strcmp(key, "background_horizon") == 0 && v >= 0 &&
				v <= 100) {
			config->glasses.background_horizon = v;
		} else if (strcmp(key, "start_distance") == 0 && v >= 0.3 &&
				v <= 20) {
			config->glasses.start_distance = v;
		} else if (strcmp(key, "steady") == 0) {
			config->glasses.steady = parse_bool(value);
		} else if (strcmp(key, "sbs_switch") == 0) {
			config->glasses.sbs_switch = parse_bool(value);
		} else if (strcmp(key, "runtime") == 0) {
			config->glasses.runtime =
				strcmp(value, "monado") == 0 ? C8_XR_RUNTIME_MONADO :
				strcmp(value, "builtin") == 0 ? C8_XR_RUNTIME_BUILTIN :
				C8_XR_RUNTIME_AUTO;
		} else if (strcmp(key, "screen") == 0) {
			int w, h;
			if (sscanf(value, "%dx%d", &w, &h) == 2 && w >= 640 &&
					h >= 480 && w <= 7680 && h <= 4320) {
				config->glasses.screen_w = w;
				config->glasses.screen_h = h;
			}
		}
	} else if (strcmp(section, "nightlight") == 0) {
		if (strcmp(key, "enabled") == 0) {
			config->night.enabled = parse_bool(value);
		} else if (strcmp(key, "temperature") == 0) {
			int k = atoi(value);
			if (k >= C8_NIGHT_MIN_K && k <= C8_NIGHT_MAX_K) {
				config->night.temperature = k;
			}
		} else if (strcmp(key, "schedule") == 0) {
			c8_night_schedule_parse(value, &config->night.schedule);
		} else if (strcmp(key, "from") == 0) {
			c8_parse_time(value, &config->night.from);
		} else if (strcmp(key, "to") == 0) {
			c8_parse_time(value, &config->night.to);
		} else if (strcmp(key, "place") == 0) {
			double lat, lon;
			config->night.has_place =
				sscanf(value, "%lf , %lf", &lat, &lon) == 2 &&
				fabs(lat) <= 90 && fabs(lon) <= 180;
			if (config->night.has_place) {
				config->night.latitude = lat;
				config->night.longitude = lon;
			}
		}
	} else if (strcmp(section, "display") == 0) {
		if (strcmp(key, "project") == 0 &&
				!c8_project_parse(value, &config->project)) {
			config->project = C8_PROJECT_AUTO;
		}
	} else if (strcmp(section, "bindings") == 0) {
		add_binding(config, key, value);
	} else if (strncmp(section, "output ", 7) == 0 && section[7]) {
		output_handler(config, section + 7, key, value);
	}
}

static const char *default_bindings[][2] = {
	{ "Super+Return", "exec @terminal" },
	{ "Super+q", "close" },
	{ "Alt+F4", "close" },
	{ "Super+Left", "snap-left" },
	{ "Super+Right", "snap-right" },
	{ "Super+Down", "unsnap" },
	{ "Super+Shift+Left", "split-left" },
	{ "Super+Shift+Right", "split-right" },
	{ "Super+Tab", "switcher" },
	{ "Alt+Tab", "switcher" },
	{ "Super+grave", "app-windows" },
	{ "Super+c", "charms" },
	{ "Super+i", "settings" },
	{ "Super+s", "search" },
	{ "Super+a", "apps" },
	{ "Super+Shift+e", "quit" },
	{ "Print", "screenshot" },
	{ "Alt+Print", "screenshot-window" },
	{ "Super+Print", "screenshot-save" },
	{ "Super+Shift+s", "snip" },
	{ "XF86AudioRaiseVolume", "volume-up" },
	{ "XF86AudioLowerVolume", "volume-down" },
	{ "XF86AudioMute", "mute" },
	{ "XF86AudioMicMute", "mic-mute" },
	{ "XF86MonBrightnessUp", "brightness-up" },
	{ "XF86MonBrightnessDown", "brightness-down" },
	{ "XF86AudioPlay", "play-pause" },
	{ "XF86AudioPause", "play-pause" },
	{ "XF86AudioNext", "next-track" },
	{ "XF86AudioPrev", "previous-track" },
	{ "XF86AudioStop", "stop-media" },
	/* Windows 8's Second screen flyout */
	{ "Super+p", "project" },
	{ "XF86Display", "project" },
	/* XR */
	{ "Super+Ctrl+space", "glasses-recentre" },
};

/* Defaults, then config.ini. Leaves dir alone. */
static void config_load(struct c8_config *config) {
	config->accent = 0x1ba1e2;
	config->background = 0x180052;
	config->pattern = C8_PATTERN_CIRCLES;
	config->more_tiles = false;
	config->live_tiles = true;
	config->has_appearance = false;
	wl_list_init(&config->bindings);
	wl_list_init(&config->outputs);
	config->terminal = strdup("foot");
	config->lock_cmd = strdup("@lock");
	config->locker = strdup("c8-lock");
	config->lock_when_off = true;
	config->project = C8_PROJECT_AUTO;
	/* XREAL One Pro's field of view; 1:1 pixels at that distance */
	config->glasses.fov = 57;
	config->glasses.distance = 2.5; // comfortable, tried in the glasses
	config->glasses.ipd = 63;
	config->glasses.screen_w = 1920;
	config->glasses.screen_h = 1080;
	config->glasses.latency = 15;
	config->glasses.scanout = -1;
	/* The 1 Pro+'s sensor, measured from the axis of a head tilt */
	config->glasses.tilt = 40;
	/* Eyes from the neck's pivot, an average head's (as Oculus's
	 * neck model): turning the head moves them */
	config->glasses.neck_up = 0.075;
	config->glasses.neck_ahead = 0.08;
	config->glasses.steady = true;
	config->glasses.background_horizon = 50;
	config->glasses.start_distance = 2.5; // as far as the windows
	config->sleep_cmd = strdup("systemctl suspend");
	config->restart_cmd = strdup("systemctl reboot");
	config->shutdown_cmd = strdup("systemctl poweroff");
	config->screen_off_after = 10;
	config->sleep_after = 30;
	config->font = strdup(C8_DEFAULT_FONT);
	config->cursor_size = C8_CURSOR_SIZE;
	config->notify_corner = strdup("top-right");
	config->night.temperature = 4000;
	config->night.from = 21 * 60;
	config->night.to = 7 * 60;
	config->clock = strdup("auto");
	config->xwayland = true;
	config->repeat_rate = 25;
	config->repeat_delay = 600;
	config->touchpad.tap = true;
	config->touchpad.natural_scroll = true;
	config->touchpad.disable_while_typing = true;

	for (size_t i = 0; i < sizeof(default_bindings) / sizeof(default_bindings[0]); i++) {
		add_binding(config, default_bindings[i][0], default_bindings[i][1]);
	}

	char path[1100];
	snprintf(path, sizeof(path), "%s/config.ini", config->dir);
	if (c8_ini_parse(config, path, config_handler)) {
		wlr_log(WLR_INFO, "Loaded %s", path);
	}
}

static void start_ini_handler(void *data, const char *section,
		const char *key, const char *value) {
	if (key && strcmp(section, "appearance") == 0) {
		appearance_handler(data, key, value);
	}
}

/* An [appearance] still in start.ini moves to config.ini, once */
static void migrate_appearance(struct c8_server *server) {
	struct c8_config *config = &server->config;
	char path[1100];
	snprintf(path, sizeof(path), "%s/start.ini", config->dir);
	if (config->has_appearance ||
			!c8_ini_parse(config, path, start_ini_handler) ||
			!config->has_appearance) {
		return;
	}
	char accent[16], background[16];
	snprintf(accent, sizeof(accent), "#%06x", config->accent & 0xffffff);
	snprintf(background, sizeof(background), "#%06x",
		config->background & 0xffffff);
	struct c8_config_op ops[] = {
		{ C8_CONFIG_SET, "appearance", "accent", accent },
		{ C8_CONFIG_SET, "appearance", "background", background },
		{ C8_CONFIG_SET, "appearance", "pattern",
			(char *)pattern_names[config->pattern] },
		{ C8_CONFIG_SET, "appearance", "more_tiles",
			config->more_tiles ? "true" : "false" },
		{ C8_CONFIG_SET, "appearance", "live_tiles",
			config->live_tiles ? "true" : "false" },
	};
	if (c8_config_patch(server, ops, sizeof(ops) / sizeof(ops[0]))) {
		wlr_log(WLR_INFO, "Moved [appearance] from start.ini to config.ini");
	}
}

void c8_config_init(struct c8_server *server, const char *dir) {
	struct c8_config *config = &server->config;
	if (dir) {
		config->dir = strdup(dir);
	} else {
		char buf[1024];
		const char *xdg = getenv("XDG_CONFIG_HOME");
		if (xdg && xdg[0]) {
			snprintf(buf, sizeof(buf), "%s/cont8nuum", xdg);
		} else {
			snprintf(buf, sizeof(buf), "%s/.config/cont8nuum",
				getenv("HOME") ? getenv("HOME") : ".");
		}
		config->dir = strdup(buf);
	}
	config_load(config);
	migrate_appearance(server);
}

void c8_config_free_file(struct c8_config *config) {
	struct c8_binding *b, *tmp;
	wl_list_for_each_safe(b, tmp, &config->bindings, link) {
		wl_list_remove(&b->link);
		free(b->arg);
		free(b);
	}
	struct c8_output_config *oc, *otmp;
	wl_list_for_each_safe(oc, otmp, &config->outputs, link) {
		wl_list_remove(&oc->link);
		free(oc->name);
		free(oc);
	}
	for (int i = 0; i < config->autostart_len; i++) {
		free(config->autostart[i]);
	}
	free(config->autostart);
	free(config->terminal);
	free(config->lock_cmd);
	free(config->locker);
	free(config->glasses.background);
	free(config->sleep_cmd);
	free(config->restart_cmd);
	free(config->shutdown_cmd);
	free(config->font);
	free(config->icon_theme);
	free(config->cursor_theme);
	free(config->notify_corner);
	free(config->clock);
	free(config->xkb_layout);
	free(config->xkb_variant);
	free(config->xkb_options);
}

void c8_config_reload(struct c8_server *server, struct c8_config *old) {
	struct c8_config *config = &server->config;
	*old = *config;
	/* The lists' heads moved: fix the neighbours' pointers to them */
	wl_list_init(&old->bindings);
	wl_list_insert_list(&old->bindings, &config->bindings);
	wl_list_init(&old->outputs);
	wl_list_insert_list(&old->outputs, &config->outputs);

	struct c8_config fresh = {
		.dir = config->dir,
	};
	*config = fresh;
	config_load(config);
}

void c8_config_finish(struct c8_server *server) {
	c8_config_free_file(&server->config);
	free(server->config.dir);
}

/*
 * config.ini editing. The file is a list of lines; edits change the lines
 * of the keys they touch and leave comments, blank lines and everything
 * else as the user wrote it.
 */

struct ini_line {
	char *text;
	char *section; // the section the line is in
	char *key; // for key = value lines, else NULL
	bool header;
};

struct ini_doc {
	struct ini_line *lines;
	int count, cap;
};

static void doc_insert(struct ini_doc *doc, int at, const char *text,
		const char *section, const char *key, bool header) {
	if (doc->count == doc->cap) {
		doc->cap = doc->cap ? doc->cap * 2 : 64;
		doc->lines = realloc(doc->lines, sizeof(*doc->lines) * doc->cap);
	}
	memmove(&doc->lines[at + 1], &doc->lines[at],
		sizeof(*doc->lines) * (doc->count - at));
	doc->lines[at] = (struct ini_line){
		.text = strdup(text),
		.section = strdup(section),
		.key = key ? strdup(key) : NULL,
		.header = header,
	};
	doc->count++;
}

static void doc_delete(struct ini_doc *doc, int at) {
	free(doc->lines[at].text);
	free(doc->lines[at].section);
	free(doc->lines[at].key);
	memmove(&doc->lines[at], &doc->lines[at + 1],
		sizeof(*doc->lines) * (doc->count - at - 1));
	doc->count--;
}

static void doc_load(struct ini_doc *doc, const char *path) {
	FILE *f = fopen(path, "r");
	if (f == NULL) {
		return;
	}
	char section[256] = "";
	char *line = NULL;
	size_t cap = 0;
	ssize_t len;
	while ((len = getline(&line, &cap, f)) > 0) {
		if (line[len - 1] == '\n') {
			line[len - 1] = '\0';
		}
		char *copy = strdup(line);
		char *s = trim(copy);
		const char *key = NULL;
		bool header = false;
		if (s[0] == '[' && strchr(s, ']')) {
			*strchr(s, ']') = '\0';
			snprintf(section, sizeof(section), "%s", trim(s + 1));
			header = true;
		} else if (s[0] != '\0' && s[0] != '#' && s[0] != ';' && strchr(s, '=')) {
			*strchr(s, '=') = '\0';
			key = trim(s);
		}
		doc_insert(doc, doc->count, line, section, key, header);
		free(copy);
	}
	free(line);
	fclose(f);
}

static bool line_is(struct ini_line *l, const char *section, const char *key) {
	return l->key && strcmp(l->section, section) == 0 &&
		(key[0] == '\0' || strcmp(l->key, key) == 0);
}

/* "#key = ..." or "# key = ..." in the section: the documented default */
static bool line_is_commented(struct ini_line *l, const char *section,
		const char *key) {
	if (l->key || l->header || strcmp(l->section, section) != 0) {
		return false;
	}
	const char *s = l->text;
	while (isspace((unsigned char)*s)) {
		s++;
	}
	if (*s != '#') {
		return false;
	}
	s++;
	while (*s == ' ') {
		s++;
	}
	size_t n = strlen(key);
	if (strncmp(s, key, n) != 0) {
		return false;
	}
	s += n;
	while (*s == ' ') {
		s++;
	}
	return *s == '=';
}

/* Where a new line for section/key goes */
static int doc_insert_point(struct ini_doc *doc, const char *section,
		const char *key) {
	int last_key = -1, header = -1, commented = -1, end = -1;
	for (int i = 0; i < doc->count; i++) {
		struct ini_line *l = &doc->lines[i];
		if (strcmp(l->section, section) != 0) {
			continue;
		}
		if (l->header && header < 0) {
			header = i;
		}
		if (header < 0) {
			continue;
		}
		if (l->key && strcmp(l->key, key) == 0) {
			last_key = i;
		} else if (commented < 0 && line_is_commented(l, section, key)) {
			commented = i;
		}
		const char *t = l->text;
		while (isspace((unsigned char)*t)) {
			t++;
		}
		if (*t) {
			end = i;
		}
	}
	if (last_key >= 0) {
		return last_key + 1;
	}
	if (commented >= 0) {
		return commented + 1;
	}
	if (header >= 0) {
		return end + 1;
	}
	/* A new section at the end */
	if (doc->count > 0 && doc->lines[doc->count - 1].text[0] != '\0') {
		doc_insert(doc, doc->count, "", "", NULL, false);
	}
	char buf[300];
	snprintf(buf, sizeof(buf), "[%s]", section);
	doc_insert(doc, doc->count, buf, section, NULL, true);
	return doc->count;
}

static void doc_add(struct ini_doc *doc, const char *section, const char *key,
		const char *value) {
	int at = doc_insert_point(doc, section, key);
	char *text;
	if (asprintf(&text, "%s = %s", key, value) < 0) {
		return;
	}
	doc_insert(doc, at, text, section, key, false);
	free(text);
}

static void doc_remove(struct ini_doc *doc, const char *section,
		const char *key) {
	for (int i = doc->count - 1; i >= 0; i--) {
		if (line_is(&doc->lines[i], section, key)) {
			doc_delete(doc, i);
		}
	}
}

/* No line breaks or section brackets sneaking in through a value */
static bool ini_safe(const char *s, bool is_key) {
	for (; *s; s++) {
		if (*s == '\n' || *s == '\r' || (is_key && (*s == '=' || *s == '[' ||
				*s == ']' || *s == '#'))) {
			return false;
		}
	}
	return true;
}

bool c8_config_patch(struct c8_server *server, const struct c8_config_op *ops,
		int count) {
	struct c8_config *config = &server->config;
	char path[1100], tmp[1110];
	snprintf(path, sizeof(path), "%s/config.ini", config->dir);
	snprintf(tmp, sizeof(tmp), "%s.tmp", path);

	struct ini_doc doc = { 0 };
	doc_load(&doc, path);
	bool replaced_bindings = false;
	for (int i = 0; i < count; i++) {
		const struct c8_config_op *op = &ops[i];
		if (!ini_safe(op->section, true) || !ini_safe(op->key, true) ||
				(op->value && !ini_safe(op->value, false))) {
			continue;
		}
		switch (op->type) {
		case C8_CONFIG_REMOVE:
			doc_remove(&doc, op->section, op->key);
			if (strcmp(op->section, "bindings") == 0 && op->key[0] == '\0') {
				replaced_bindings = true;
			}
			break;
		case C8_CONFIG_SET: {
			int first = -1;
			for (int j = 0; j < doc.count; j++) {
				if (line_is(&doc.lines[j], op->section, op->key)) {
					first = j;
					break;
				}
			}
			if (first < 0) {
				doc_add(&doc, op->section, op->key, op->value);
				break;
			}
			for (int j = doc.count - 1; j > first; j--) {
				if (line_is(&doc.lines[j], op->section, op->key)) {
					doc_delete(&doc, j);
				}
			}
			free(doc.lines[first].text);
			if (asprintf(&doc.lines[first].text, "%s = %s", op->key,
					op->value) < 0) {
				doc.lines[first].text = strdup("");
			}
			break;
		}
		case C8_CONFIG_ADD:
			doc_add(&doc, op->section, op->key, op->value);
			break;
		}
	}

	/* A replaced list of bindings drops built-in ones by binding them
	 * to none */
	if (replaced_bindings) {
		for (size_t i = 0; i < sizeof(default_bindings) / sizeof(default_bindings[0]); i++) {
			uint32_t dmods, mods;
			xkb_keysym_t dsym, sym;
			c8_parse_combo(default_bindings[i][0], &dmods, &dsym);
			bool kept = false;
			for (int j = 0; j < doc.count && !kept; j++) {
				struct ini_line *l = &doc.lines[j];
				kept = line_is(l, "bindings", "") &&
					c8_parse_combo(l->key, &mods, &sym) &&
					mods == dmods && sym == dsym;
			}
			if (!kept) {
				doc_add(&doc, "bindings", default_bindings[i][0], "none");
			}
		}
	}

	bool ok = mkdir_p(config->dir) == 0;
	FILE *f = ok ? fopen(tmp, "w") : NULL;
	if (f) {
		for (int i = 0; i < doc.count; i++) {
			fprintf(f, "%s\n", doc.lines[i].text);
		}
		ok = fclose(f) == 0 && rename(tmp, path) == 0;
	} else {
		ok = false;
	}
	if (!ok) {
		wlr_log_errno(WLR_ERROR, "Failed to save %s", path);
		unlink(tmp);
	}
	for (int i = 0; i < doc.count; i++) {
		free(doc.lines[i].text);
		free(doc.lines[i].section);
		free(doc.lines[i].key);
	}
	free(doc.lines);
	return ok;
}
