/*
 * See LICENSE file for copyright and license details.
 *
 * Lua configuration loader for ether.
 */
#include <lauxlib.h>
#include <lua.h>
#include <lualib.h>

#include "ether.h"

/* initial capacity for dynamic arrays */
#define INIT_CAP 16

/* layout function registry - built-in layouts available from Lua */
typedef struct {
	const char *name;
	void (*arrange)(Monitor *);
} LayoutFunc;

static const LayoutFunc layout_funcs[] = {
	{ "tile",    tile },
	{ "float",   NULL },
	{ "monocle", monocle },
};

#define NUM_LAYOUT_FUNCS (sizeof(layout_funcs) / sizeof(layout_funcs[0]))

/* current config file path (for reload) */
static char *current_config_path = NULL;

/* default config path buffer */
static char default_config_path[PATH_MAX];

/* forward declarations */
static const char *lua_getfield_string(lua_State *L, int idx, const char *key);

/* spawn argv allocations, freed on config reload */
static char ***spawn_argv = NULL;
static int nspawn_argv = 0;
static int spawn_argv_cap = 0;

/* config arrays - dynamically allocated */
static int keys_cap = 0;
static int buttons_cap = 0;
static int rules_cap = 0;
static int layouts_cap = 0;
static int monrules_cap = 0;

/* pending layout names for monitor rules, resolved once all layouts are parsed */
static char **monrule_layout_names = NULL;
static int monrule_layout_cap = 0;

/* config variables with defaults */
int sloppyfocus               = 1;
int bypass_surface_visibility = 0;
unsigned int borderpx         = 1;
float rootcolor[4]            = {0.133f, 0.133f, 0.133f, 1.0f};
float bordercolor[4]          = {0.267f, 0.267f, 0.267f, 1.0f};
float focuscolor[4]           = {0.0f, 0.333f, 0.467f, 1.0f};
float urgentcolor[4]          = {1.0f, 0.0f, 0.0f, 1.0f};
float fullscreen_bg[4]        = {0.0f, 0.0f, 0.0f, 1.0f};

int log_level = WLR_ERROR;

Rule *rules = NULL;
int nrrules = 0;

Layout *layouts = NULL;
int nrlayouts = 0;

MonitorRule *monrules = NULL;
int nrmonrules = 0;

struct xkb_rule_names xkb_rules = {
	.rules = NULL,
	.model = NULL,
	.layout = NULL,
	.variant = NULL,
	.options = NULL,
};

int repeat_rate = 25;
int repeat_delay = 600;

int tap_to_click = 1;
int tap_and_drag = 1;
int drag_lock = 1;
int natural_scrolling = 0;
int disable_while_typing = 1;
int left_handed = 0;
int middle_button_emulation = 0;
enum libinput_config_scroll_method scroll_method = LIBINPUT_CONFIG_SCROLL_2FG;
enum libinput_config_click_method click_method = LIBINPUT_CONFIG_CLICK_METHOD_BUTTON_AREAS;
uint32_t send_events_mode = LIBINPUT_CONFIG_SEND_EVENTS_ENABLED;
enum libinput_config_accel_profile accel_profile = LIBINPUT_CONFIG_ACCEL_PROFILE_ADAPTIVE;
double accel_speed = 0.0;
enum libinput_config_tap_button_map button_map = LIBINPUT_CONFIG_TAP_MAP_LRM;

Key *keys = NULL;
int nrkeys = 0;
Button *buttons = NULL;
int nrbuttons = 0;

/* ensure minimum allocation */
static void *
ensure_cap(void *arr, int *cap, int count, int size)
{
	if (*cap >= count)
		return arr;
	while (*cap < count)
		*cap = *cap ? *cap * 2 : INIT_CAP;
	return realloc(arr, *cap * size);
}

/* helper: parse a hex color string like "#RRGGBB" or "#RRGGBBAA" into 4 floats */
static int
parse_color(lua_State *L, int idx, float color[4])
{
	const char *hex;
	size_t len;
	uint32_t rgba;

	if (!lua_isstring(L, idx))
		return 0;

	hex = lua_tolstring(L, idx, &len);
	if (len != 7 && len != 9)
		return 0;
	if (hex[0] != '#')
		return 0;

	rgba = (uint32_t)strtoul(hex + 1, NULL, 16);
	if (len == 7)
		rgba = (rgba << 8) | 0xFF;

	color[0] = ((rgba >> 24) & 0xFF) / 255.0f;
	color[1] = ((rgba >> 16) & 0xFF) / 255.0f;
	color[2] = ((rgba >> 8) & 0xFF) / 255.0f;
	color[3] = (rgba & 0xFF) / 255.0f;
	return 1;
}

/* helper: lookup a layout function by name */
static void (*
lookup_layout_func(const char *name))(Monitor *)
{
	size_t i;
	for (i = 0; i < NUM_LAYOUT_FUNCS; i++)
		if (strcmp(name, layout_funcs[i].name) == 0)
			return layout_funcs[i].arrange;
	return NULL;
}

/* helper: find layout by name in current layouts array */
static const Layout *
find_layout(const char *name)
{
	int i;
	for (i = 0; i < nrlayouts; i++)
		if (layouts[i].symbol && strcmp(layouts[i].symbol, name) == 0)
			return &layouts[i];
	return NULL;
}

/* Lua API: ether.color("#RRGGBB") -> r, g, b, a */
static int
l_ether_color(lua_State *L)
{
	float color[4];
	if (!parse_color(L, 1, color))
		return luaL_error(L, "invalid color, expected '#RRGGBB' or '#RRGGBBAA'");
	lua_pushnumber(L, color[0]);
	lua_pushnumber(L, color[1]);
	lua_pushnumber(L, color[2]);
	lua_pushnumber(L, color[3]);
	return 4;
}

/* Lua API: ether.spawn(cmd_string) - spawn a program immediately */
static int
l_ether_spawn(lua_State *L)
{
	const char *cmd = luaL_checkstring(L, 1);
	Arg arg = {.v = (const char *[]){ "/bin/sh", "-c", cmd, NULL }};
	spawn(&arg);
	return 0;
}

/* Lua API: ether.sloppy_focus(enabled) */
static int
l_ether_sloppy_focus(lua_State *L)
{
	sloppyfocus = lua_toboolean(L, 1);
	return 0;
}

/* Lua API: ether.bypass_surface_visibility(enabled) */
static int
l_ether_bypass_surface_visibility(lua_State *L)
{
	bypass_surface_visibility = lua_toboolean(L, 1);
	return 0;
}

/* Lua API: ether.border_width(px) */
static int
l_ether_border_width(lua_State *L)
{
	borderpx = (unsigned int)luaL_checkinteger(L, 1);
	return 0;
}

/* Lua API: ether.border_color(hex) */
static int
l_ether_border_color(lua_State *L)
{
	if (!parse_color(L, 1, bordercolor))
		return luaL_error(L, "invalid color");
	return 0;
}

/* Lua API: ether.focus_color(hex) */
static int
l_ether_focus_color(lua_State *L)
{
	if (!parse_color(L, 1, focuscolor))
		return luaL_error(L, "invalid color");
	return 0;
}

/* Lua API: ether.urgent_color(hex) */
static int
l_ether_urgent_color(lua_State *L)
{
	if (!parse_color(L, 1, urgentcolor))
		return luaL_error(L, "invalid color");
	return 0;
}

/* Lua API: ether.root_color(hex) */
static int
l_ether_root_color(lua_State *L)
{
	if (!parse_color(L, 1, rootcolor))
		return luaL_error(L, "invalid color");
	return 0;
}

/* Lua API: ether.fullscreen_bg(hex) */
static int
l_ether_fullscreen_bg(lua_State *L)
{
	if (!parse_color(L, 1, fullscreen_bg))
		return luaL_error(L, "invalid color");
	return 0;
}

/* Lua API: ether.log_level(level) */
static int
l_ether_log_level(lua_State *L)
{
	const char *s = luaL_checkstring(L, 1);
	if (strcmp(s, "silent") == 0 || strcmp(s, "SILENT") == 0)
		log_level = WLR_SILENT;
	else if (strcmp(s, "error") == 0 || strcmp(s, "ERROR") == 0)
		log_level = WLR_ERROR;
	else if (strcmp(s, "info") == 0 || strcmp(s, "INFO") == 0)
		log_level = WLR_INFO;
	else if (strcmp(s, "debug") == 0 || strcmp(s, "DEBUG") == 0)
		log_level = WLR_DEBUG;
	else
		return luaL_error(L, "invalid log level: %s", s);
	return 0;
}

/* Lua API: ether.xkb_rules(opts_table) */
static int
l_ether_xkb_rules(lua_State *L)
{
	const char *s;
	if (!lua_istable(L, 1))
		return luaL_error(L, "expected table");

	s = lua_getfield_string(L, 1, "rules");
	if (s) xkb_rules.rules = strdup(s);

	s = lua_getfield_string(L, 1, "model");
	if (s) xkb_rules.model = strdup(s);

	s = lua_getfield_string(L, 1, "layout");
	if (s) xkb_rules.layout = strdup(s);

	s = lua_getfield_string(L, 1, "variant");
	if (s) xkb_rules.variant = strdup(s);

	s = lua_getfield_string(L, 1, "options");
	if (s) xkb_rules.options = strdup(s);

	return 0;
}

/* Lua API: ether.repeat_rate(rate) */
static int
l_ether_repeat_rate(lua_State *L)
{
	repeat_rate = (int)luaL_checkinteger(L, 1);
	return 0;
}

/* Lua API: ether.repeat_delay(delay) */
static int
l_ether_repeat_delay(lua_State *L)
{
	repeat_delay = (int)luaL_checkinteger(L, 1);
	return 0;
}

/* Lua API: ether.trackpad(opts_table) */
static int
l_ether_trackpad(lua_State *L)
{
	if (!lua_istable(L, 1))
		return luaL_error(L, "expected table");

	lua_getfield(L, 1, "tap_to_click");
	if (!lua_isnil(L, -1))
		tap_to_click = lua_toboolean(L, -1);
	lua_pop(L, 1);

	lua_getfield(L, 1, "tap_and_drag");
	if (!lua_isnil(L, -1))
		tap_and_drag = lua_toboolean(L, -1);
	lua_pop(L, 1);

	lua_getfield(L, 1, "drag_lock");
	if (!lua_isnil(L, -1))
		drag_lock = lua_toboolean(L, -1);
	lua_pop(L, 1);

	lua_getfield(L, 1, "natural_scrolling");
	if (!lua_isnil(L, -1))
		natural_scrolling = lua_toboolean(L, -1);
	lua_pop(L, 1);

	lua_getfield(L, 1, "disable_while_typing");
	if (!lua_isnil(L, -1))
		disable_while_typing = lua_toboolean(L, -1);
	lua_pop(L, 1);

	lua_getfield(L, 1, "left_handed");
	if (!lua_isnil(L, -1))
		left_handed = lua_toboolean(L, -1);
	lua_pop(L, 1);

	lua_getfield(L, 1, "middle_button_emulation");
	if (!lua_isnil(L, -1))
		middle_button_emulation = lua_toboolean(L, -1);
	lua_pop(L, 1);

	lua_getfield(L, 1, "accel_speed");
	if (!lua_isnil(L, -1))
		accel_speed = lua_tonumber(L, -1);
	lua_pop(L, 1);

	lua_getfield(L, 1, "scroll_method");
	if (!lua_isnil(L, -1)) {
		const char *s = lua_tostring(L, -1);
		if (s) {
			if (strcmp(s, "no_scroll") == 0)
				scroll_method = LIBINPUT_CONFIG_SCROLL_NO_SCROLL;
			else if (strcmp(s, "2fg") == 0)
				scroll_method = LIBINPUT_CONFIG_SCROLL_2FG;
			else if (strcmp(s, "edge") == 0)
				scroll_method = LIBINPUT_CONFIG_SCROLL_EDGE;
			else if (strcmp(s, "on_button_down") == 0)
				scroll_method = LIBINPUT_CONFIG_SCROLL_ON_BUTTON_DOWN;
		}
	}
	lua_pop(L, 1);

	lua_getfield(L, 1, "click_method");
	if (!lua_isnil(L, -1)) {
		const char *s = lua_tostring(L, -1);
		if (s) {
			if (strcmp(s, "none") == 0)
				click_method = LIBINPUT_CONFIG_CLICK_METHOD_NONE;
			else if (strcmp(s, "button_areas") == 0)
				click_method = LIBINPUT_CONFIG_CLICK_METHOD_BUTTON_AREAS;
			else if (strcmp(s, "clickfinger") == 0)
				click_method = LIBINPUT_CONFIG_CLICK_METHOD_CLICKFINGER;
		}
	}
	lua_pop(L, 1);

	lua_getfield(L, 1, "send_events");
	if (!lua_isnil(L, -1)) {
		const char *s = lua_tostring(L, -1);
		if (s) {
			if (strcmp(s, "enabled") == 0)
				send_events_mode = LIBINPUT_CONFIG_SEND_EVENTS_ENABLED;
			else if (strcmp(s, "disabled") == 0)
				send_events_mode = LIBINPUT_CONFIG_SEND_EVENTS_DISABLED;
			else if (strcmp(s, "disabled_on_external_mouse") == 0)
				send_events_mode = LIBINPUT_CONFIG_SEND_EVENTS_DISABLED_ON_EXTERNAL_MOUSE;
		}
	}
	lua_pop(L, 1);

	lua_getfield(L, 1, "accel_profile");
	if (!lua_isnil(L, -1)) {
		const char *s = lua_tostring(L, -1);
		if (s) {
			if (strcmp(s, "flat") == 0)
				accel_profile = LIBINPUT_CONFIG_ACCEL_PROFILE_FLAT;
			else if (strcmp(s, "adaptive") == 0)
				accel_profile = LIBINPUT_CONFIG_ACCEL_PROFILE_ADAPTIVE;
		}
	}
	lua_pop(L, 1);

	lua_getfield(L, 1, "button_map");
	if (!lua_isnil(L, -1)) {
		const char *s = lua_tostring(L, -1);
		if (s) {
			if (strcmp(s, "lrm") == 0)
				button_map = LIBINPUT_CONFIG_TAP_MAP_LRM;
			else if (strcmp(s, "lmr") == 0)
				button_map = LIBINPUT_CONFIG_TAP_MAP_LMR;
		}
	}
	lua_pop(L, 1);

	return 0;
}

/* helper: get string field from table at stack index */
static const char *
lua_getfield_string(lua_State *L, int idx, const char *key)
{
	const char *s;
	lua_getfield(L, idx, key);
	if (lua_isnil(L, -1)) {
		lua_pop(L, 1);
		return NULL;
	}
	s = lua_tostring(L, -1);
	lua_pop(L, 1);
	return s;
}

/* Lua API: ether.rule(opts_table) */
static int
l_ether_rule(lua_State *L)
{
	const char *s;

	if (!lua_istable(L, 1))
		return luaL_error(L, "expected table");

	/* ensure minimum capacity */
	rules = ensure_cap(rules, &rules_cap, nrrules + 1, sizeof(Rule));
	memset(&rules[nrrules], 0, sizeof(Rule));

	s = lua_getfield_string(L, 1, "app_id");
	if (s) rules[nrrules].id = strdup(s);

	s = lua_getfield_string(L, 1, "title");
	if (s) rules[nrrules].title = strdup(s);

	lua_getfield(L, 1, "tags");
	if (!lua_isnil(L, -1))
		rules[nrrules].tags = (uint32_t)lua_tointeger(L, -1);
	lua_pop(L, 1);

	lua_getfield(L, 1, "float");
	if (!lua_isnil(L, -1))
		rules[nrrules].isfloating = lua_toboolean(L, -1);
	lua_pop(L, 1);

	lua_getfield(L, 1, "monitor");
	if (!lua_isnil(L, -1))
		rules[nrrules].monitor = (int)lua_tointeger(L, -1);
	else
		rules[nrrules].monitor = -1;
	lua_pop(L, 1);

	nrrules++;
	return 0;
}

/* Lua API: ether.layout(opts_table) */
static int
l_ether_layout(lua_State *L)
{
	const char *sym;
	const char *func_name;
	void (*func)(Monitor *);

	if (!lua_istable(L, 1))
		return luaL_error(L, "expected table");

	sym = lua_getfield_string(L, 1, "name");
	if (!sym)
		return luaL_error(L, "layout requires 'name'");

	func_name = lua_getfield_string(L, 1, "arrange");
	if (!func_name)
		return luaL_error(L, "layout requires 'arrange'");

	/* validate the layout function before allocating an entry */
	if (strcmp(func_name, "float") == 0)
		func = NULL;
	else if ((func = lookup_layout_func(func_name)))
		;
	else
		return luaL_error(L, "unknown layout function: %s", func_name);

	layouts = ensure_cap(layouts, &layouts_cap, nrlayouts + 1, sizeof(Layout));
	layouts[nrlayouts].symbol = strdup(sym);
	layouts[nrlayouts].arrange = func;
	nrlayouts++;
	return 0;
}

/* Lua API: ether.monitor(opts_table) */
static int
l_ether_monitor(lua_State *L)
{
	const char *s;
	const char *layout_name;

	if (!lua_istable(L, 1))
		return luaL_error(L, "expected table");

	monrules = ensure_cap(monrules, &monrules_cap, nrmonrules + 1, sizeof(MonitorRule));
	memset(&monrules[nrmonrules], 0, sizeof(MonitorRule));

	/* reserve a slot for potential deferred layout name resolution */
	monrule_layout_names = ensure_cap(monrule_layout_names, &monrule_layout_cap,
			nrmonrules + 1, sizeof(char *));
	monrule_layout_names[nrmonrules] = NULL;

	s = lua_getfield_string(L, 1, "name");
	if (s) monrules[nrmonrules].name = strdup(s);

	lua_getfield(L, 1, "mfact");
	if (!lua_isnil(L, -1))
		monrules[nrmonrules].mfact = (float)lua_tonumber(L, -1);
	else
		monrules[nrmonrules].mfact = 0.55f;
	lua_pop(L, 1);

	lua_getfield(L, 1, "nmaster");
	if (!lua_isnil(L, -1))
		monrules[nrmonrules].nmaster = (int)lua_tointeger(L, -1);
	else
		monrules[nrmonrules].nmaster = 1;
	lua_pop(L, 1);

	lua_getfield(L, 1, "scale");
	if (!lua_isnil(L, -1))
		monrules[nrmonrules].scale = (float)lua_tonumber(L, -1);
	else
		monrules[nrmonrules].scale = 1.0f;
	lua_pop(L, 1);

	layout_name = lua_getfield_string(L, 1, "layout");
	if (layout_name) {
		if (find_layout(layout_name))
			monrules[nrmonrules].lt = find_layout(layout_name);
		else
			/* layout not defined yet - defer resolution until the whole
			 * config file has been parsed */
			monrule_layout_names[nrmonrules] = strdup(layout_name);
	} else if (nrlayouts > 0) {
		monrules[nrmonrules].lt = &layouts[0];
	}

	lua_getfield(L, 1, "transform");
	if (!lua_isnil(L, -1)) {
		const char *t = lua_tostring(L, -1);
		if (t) {
			if (strcmp(t, "normal") == 0 || strcmp(t, "none") == 0)
				monrules[nrmonrules].rr = WL_OUTPUT_TRANSFORM_NORMAL;
			else if (strcmp(t, "90") == 0)
				monrules[nrmonrules].rr = WL_OUTPUT_TRANSFORM_90;
			else if (strcmp(t, "180") == 0)
				monrules[nrmonrules].rr = WL_OUTPUT_TRANSFORM_180;
			else if (strcmp(t, "270") == 0)
				monrules[nrmonrules].rr = WL_OUTPUT_TRANSFORM_270;
			else if (strcmp(t, "flipped") == 0)
				monrules[nrmonrules].rr = WL_OUTPUT_TRANSFORM_FLIPPED;
			else if (strcmp(t, "flipped_90") == 0)
				monrules[nrmonrules].rr = WL_OUTPUT_TRANSFORM_FLIPPED_90;
			else if (strcmp(t, "flipped_180") == 0)
				monrules[nrmonrules].rr = WL_OUTPUT_TRANSFORM_FLIPPED_180;
			else if (strcmp(t, "flipped_270") == 0)
				monrules[nrmonrules].rr = WL_OUTPUT_TRANSFORM_FLIPPED_270;
		}
	}
	lua_pop(L, 1);

	monrules[nrmonrules].x = -1;
	monrules[nrmonrules].y = -1;
	lua_getfield(L, 1, "x");
	if (!lua_isnil(L, -1))
		monrules[nrmonrules].x = (int)lua_tointeger(L, -1);
	lua_pop(L, 1);

	lua_getfield(L, 1, "y");
	if (!lua_isnil(L, -1))
		monrules[nrmonrules].y = (int)lua_tointeger(L, -1);
	lua_pop(L, 1);

	nrmonrules++;
	return 0;
}

/* helper: convert modifier string to wlr modifier mask */
static uint32_t
parse_modifier(const char *s)
{
	if (strcmp(s, "ALT") == 0 || strcmp(s, "Mod1") == 0)
		return WLR_MODIFIER_ALT;
	if (strcmp(s, "CTRL") == 0 || strcmp(s, "Control") == 0 || strcmp(s, "Ctrl") == 0 || strcmp(s, "Mod4") == 0)
		return WLR_MODIFIER_CTRL;
	if (strcmp(s, "SHIFT") == 0 || strcmp(s, "Shift") == 0 || strcmp(s, "Mod1Shift") == 0)
		return WLR_MODIFIER_SHIFT;
	if (strcmp(s, "SUPER") == 0 || strcmp(s, "Mod4") == 0)
		return WLR_MODIFIER_LOGO;
	if (strcmp(s, "MODKEY") == 0)
		return WLR_MODIFIER_ALT; /* default MODKEY is Alt */
	return 0;
}

/* helper: convert modifier table to mask */
static uint32_t
parse_modifiers(lua_State *L, int idx)
{
	uint32_t mods = 0;
	int i, n;

	if (!lua_istable(L, idx))
		return 0;

	n = (int)lua_rawlen(L, idx);
	for (i = 1; i <= n; i++) {
		lua_rawgeti(L, idx, i);
		if (lua_isstring(L, -1))
			mods |= parse_modifier(lua_tostring(L, -1));
		lua_pop(L, 1);
	}
	return mods;
}

/* helper: resolve a keysym string to xkb_keysym_t */
static xkb_keysym_t
resolve_keysym(const char *name)
{
	xkb_keysym_t sym;
	/* try XKB keysym first */
	sym = xkb_keysym_from_name(name, XKB_KEYSYM_NO_FLAGS);
	if (sym != XKB_KEYSYM_NO_FLAGS)
		return sym;
	/* try case-insensitive */
	sym = xkb_keysym_from_name(name, XKB_KEYSYM_CASE_INSENSITIVE);
	return sym;
}

/* helper: get the arg for a keybind action */
static Arg
get_action_arg(lua_State *L, int idx, const char *action)
{
	Arg arg = {0};

	if (strcmp(action, "spawn") == 0) {
		const char *cmd;
		char **argv;

		if (lua_istable(L, idx)) {
			/* table of arguments -> execvp directly */
			int n = (int)lua_rawlen(L, idx);
			int i;
			argv = calloc(n + 1, sizeof(char *));
			for (i = 0; i < n; i++) {
				lua_rawgeti(L, idx, i + 1);
				cmd = lua_tostring(L, -1);
				argv[i] = cmd ? strdup(cmd) : strdup("");
				lua_pop(L, 1);
			}
			argv[n] = NULL;
		} else {
			/* single string -> run via shell */
			cmd = luaL_checkstring(L, idx);
			argv = calloc(4, sizeof(char *));
			argv[0] = strdup("/bin/sh");
			argv[1] = strdup("-c");
			argv[2] = strdup(cmd);
			argv[3] = NULL;
		}

		/* track allocation for later freeing */
		spawn_argv = ensure_cap(spawn_argv, &spawn_argv_cap, nspawn_argv + 1,
				sizeof(char **));
		spawn_argv[nspawn_argv++] = argv;
		arg.v = argv;
	} else if (lua_istable(L, idx)) {
		if (strcmp(action, "view") == 0) {
			lua_getfield(L, idx, "tag");
			if (!lua_isnil(L, -1))
				arg.ui = 1u << (uint32_t)lua_tointeger(L, -1);
			lua_pop(L, 1);
		} else if (strcmp(action, "toggleview") == 0) {
			lua_getfield(L, idx, "tag");
			if (!lua_isnil(L, -1))
				arg.ui = 1u << (uint32_t)lua_tointeger(L, -1);
			lua_pop(L, 1);
		} else if (strcmp(action, "tag") == 0) {
			lua_getfield(L, idx, "tag");
			if (!lua_isnil(L, -1))
				arg.ui = 1u << (uint32_t)lua_tointeger(L, -1);
			lua_pop(L, 1);
		} else if (strcmp(action, "toggletag") == 0) {
			lua_getfield(L, idx, "tag");
			if (!lua_isnil(L, -1))
				arg.ui = 1u << (uint32_t)lua_tointeger(L, -1);
			lua_pop(L, 1);
		} else if (strcmp(action, "incnmaster") == 0) {
			lua_getfield(L, idx, "delta");
			if (!lua_isnil(L, -1))
				arg.i = (int)lua_tointeger(L, -1);
			lua_pop(L, 1);
		} else if (strcmp(action, "setmfact") == 0) {
			lua_getfield(L, idx, "delta");
			if (!lua_isnil(L, -1))
				arg.f = (float)lua_tonumber(L, -1);
			lua_pop(L, 1);
		} else if (strcmp(action, "focusmon") == 0) {
			const char *dir;
			lua_getfield(L, idx, "direction");
			dir = lua_tostring(L, -1);
			if (dir && strcmp(dir, "left") == 0)
				arg.i = WLR_DIRECTION_LEFT;
			else
				arg.i = WLR_DIRECTION_RIGHT;
			lua_pop(L, 1);
		} else if (strcmp(action, "tagmon") == 0) {
			const char *dir;
			lua_getfield(L, idx, "direction");
			dir = lua_tostring(L, -1);
			if (dir && strcmp(dir, "left") == 0)
				arg.i = WLR_DIRECTION_LEFT;
			else
				arg.i = WLR_DIRECTION_RIGHT;
			lua_pop(L, 1);
		} else if (strcmp(action, "setlayout") == 0) {
			const char *name;
			lua_getfield(L, idx, "layout");
			name = lua_tostring(L, -1);
			if (name) {
				const Layout *l = find_layout(name);
				if (l) arg.v = (void *)l;
			}
			lua_pop(L, 1);
		} else if (strcmp(action, "focusstack") == 0) {
			lua_getfield(L, idx, "delta");
			if (!lua_isnil(L, -1))
				arg.i = (int)lua_tointeger(L, -1);
			else
				arg.i = 1;
			lua_pop(L, 1);
		} else if (strcmp(action, "moveresize") == 0) {
			const char *mode;
			lua_getfield(L, idx, "mode");
			mode = lua_tostring(L, -1);
			if (mode && strcmp(mode, "resize") == 0)
				arg.ui = CurResize;
			else
				arg.ui = CurMove;
			lua_pop(L, 1);
		} else if (strcmp(action, "chvt") == 0) {
			lua_getfield(L, idx, "vt");
			if (!lua_isnil(L, -1))
				arg.ui = (unsigned int)lua_tointeger(L, -1);
			lua_pop(L, 1);
		}
	}
	/* for quit, killclient, zoom, togglefloating, togglefullscreen, reload or a
	 * missing/non-table arg: arg stays {0} */

	return arg;
}

/* helper: lookup function pointer by action name */
static void (*
lookup_action(const char *name))(const Arg *)
{
	static const struct {
		const char *name;
		void (*func)(const Arg *);
	} actions[] = {
		{ "spawn",             spawn },
		{ "focusstack",        focusstack },
		{ "incnmaster",        incnmaster },
		{ "setmfact",          setmfact },
		{ "zoom",              zoom },
		{ "view",              view },
		{ "toggleview",        toggleview },
		{ "tag",               tag },
		{ "toggletag",         toggletag },
		{ "focusmon",          focusmon },
		{ "tagmon",            tagmon },
		{ "setlayout",         setlayout },
		{ "togglefloating",    togglefloating },
		{ "togglefullscreen",  togglefullscreen },
		{ "killclient",        killclient },
		{ "moveresize",        moveresize },
		{ "quit",              quit },
		{ "reload",            reload },
		{ "chvt",              chvt },
	};
	size_t i;
	for (i = 0; i < sizeof(actions) / sizeof(actions[0]); i++)
		if (strcmp(name, actions[i].name) == 0)
			return actions[i].func;
	return NULL;
}

/* Lua API: ether.key(opts_table) */
static int
l_ether_key(lua_State *L)
{
	const char *s;
	const char *action;

	if (!lua_istable(L, 1))
		return luaL_error(L, "expected table");

	keys = ensure_cap(keys, &keys_cap, nrkeys + 1, sizeof(Key));
	memset(&keys[nrkeys], 0, sizeof(Key));

	/* modifiers */
	lua_getfield(L, 1, "mods");
	if (!lua_isnil(L, -1))
		keys[nrkeys].mod = parse_modifiers(L, -1);
	lua_pop(L, 1);

	/* key */
	s = lua_getfield_string(L, 1, "key");
	if (!s)
		return luaL_error(L, "key requires 'key'");
	keys[nrkeys].keysym = resolve_keysym(s);
	if (keys[nrkeys].keysym == XKB_KEYSYM_NO_FLAGS)
		return luaL_error(L, "unknown keysym: %s", s);

	/* action */
	action = lua_getfield_string(L, 1, "action");
	if (!action)
		return luaL_error(L, "key requires 'action'");
	keys[nrkeys].func = lookup_action(action);
	if (!keys[nrkeys].func)
		return luaL_error(L, "unknown action: %s", action);

	/* arg */
	lua_getfield(L, 1, "arg");
	{
		Arg tmp = get_action_arg(L, -1, action);
		memcpy((void *)&keys[nrkeys].arg, &tmp, sizeof(Arg));
	}
	lua_pop(L, 1);

	nrkeys++;
	return 0;
}

/* Lua API: ether.mouse(opts_table) */
static int
l_ether_mouse(lua_State *L)
{
	const char *s;

	if (!lua_istable(L, 1))
		return luaL_error(L, "expected table");

	buttons = ensure_cap(buttons, &buttons_cap, nrbuttons + 1, sizeof(Button));
	memset(&buttons[nrbuttons], 0, sizeof(Button));

	/* mods */
	lua_getfield(L, 1, "mods");
	if (!lua_isnil(L, -1))
		buttons[nrbuttons].mod = parse_modifiers(L, -1);
	lua_pop(L, 1);

	/* button */
	s = lua_getfield_string(L, 1, "button");
	if (!s)
		return luaL_error(L, "mouse requires 'button'");
	if (strcmp(s, "left") == 0 || strcmp(s, "BTN_LEFT") == 0)
		buttons[nrbuttons].button = BTN_LEFT;
	else if (strcmp(s, "middle") == 0 || strcmp(s, "BTN_MIDDLE") == 0)
		buttons[nrbuttons].button = BTN_MIDDLE;
	else if (strcmp(s, "right") == 0 || strcmp(s, "BTN_RIGHT") == 0)
		buttons[nrbuttons].button = BTN_RIGHT;
	else
		buttons[nrbuttons].button = (unsigned int)strtoul(s, NULL, 0);

	/* action */
	s = lua_getfield_string(L, 1, "action");
	if (s)
		buttons[nrbuttons].func = lookup_action(s);

	/* arg */
	lua_getfield(L, 1, "arg");
	if (s) {
		Arg tmp = get_action_arg(L, -1, s);
		memcpy((void *)&buttons[nrbuttons].arg, &tmp, sizeof(Arg));
	}
	lua_pop(L, 1);

	nrbuttons++;
	return 0;
}

/* Lua API: ether.tags(count) or ether.tags({ mods = {...} }, count) - generates
 * standard tag keybindings */
static int
l_ether_tags(lua_State *L)
{
	int ntags;
	int i;
	uint32_t mod = WLR_MODIFIER_ALT; /* default MODKEY */

	if (lua_istable(L, 1)) {
		/* optional modifier table */
		lua_getfield(L, 1, "mods");
		if (!lua_isnil(L, -1) && lua_istable(L, -1))
			mod = parse_modifiers(L, -1);
		lua_pop(L, 1);
		ntags = (int)luaL_checkinteger(L, 2);
	} else {
		ntags = (int)luaL_checkinteger(L, 1);
	}

	for (i = 0; i < ntags && i < 32; i++) {
		uint32_t tag_mask = 1u << i;
		Arg tmparg;

		/* MODKEY+tag -> view */
		keys = ensure_cap(keys, &keys_cap, nrkeys + 1, sizeof(Key));
		keys[nrkeys].mod = mod;
		keys[nrkeys].func = view;
		tmparg.ui = tag_mask;
		memcpy((void *)&keys[nrkeys].arg, &tmparg, sizeof(Arg));
		nrkeys++;

		/* MODKEY+CTRL+tag -> toggleview */
		keys = ensure_cap(keys, &keys_cap, nrkeys + 1, sizeof(Key));
		keys[nrkeys].mod = mod | WLR_MODIFIER_CTRL;
		keys[nrkeys].func = toggleview;
		tmparg.ui = tag_mask;
		memcpy((void *)&keys[nrkeys].arg, &tmparg, sizeof(Arg));
		nrkeys++;

		/* MODKEY+SHIFT+tag -> tag */
		keys = ensure_cap(keys, &keys_cap, nrkeys + 1, sizeof(Key));
		keys[nrkeys].mod = mod | WLR_MODIFIER_SHIFT;
		keys[nrkeys].func = tag;
		tmparg.ui = tag_mask;
		memcpy((void *)&keys[nrkeys].arg, &tmparg, sizeof(Arg));
		nrkeys++;

		/* MODKEY+CTRL+SHIFT+tag -> toggletag */
		keys = ensure_cap(keys, &keys_cap, nrkeys + 1, sizeof(Key));
		keys[nrkeys].mod = mod | WLR_MODIFIER_CTRL | WLR_MODIFIER_SHIFT;
		keys[nrkeys].func = toggletag;
		tmparg.ui = tag_mask;
		memcpy((void *)&keys[nrkeys].arg, &tmparg, sizeof(Arg));
		nrkeys++;
	}

	return 0;
}

/* Lua API: ether.tags_with(mods, keysym_table, tag) - bind specific keys to tag actions */
static int
l_ether_tags_with(lua_State *L)
{
	uint32_t mod;
	uint32_t tag_mask;
	int i, n;

	mod = parse_modifiers(L, 1);

	tag_mask = (uint32_t)luaL_checkinteger(L, 3);

	if (!lua_istable(L, 2))
		return luaL_error(L, "expected keysym table");

	n = (int)lua_rawlen(L, 2);
	for (i = 1; i <= n; i++) {
		const char *s;
		xkb_keysym_t sym;
		Arg tmparg;

		lua_rawgeti(L, 2, i);
		s = lua_tostring(L, -1);
		lua_pop(L, 1);
		if (!s) continue;

		sym = resolve_keysym(s);
		if (sym == XKB_KEYSYM_NO_FLAGS)
			continue;

		/* view */
		keys = ensure_cap(keys, &keys_cap, nrkeys + 1, sizeof(Key));
		keys[nrkeys].mod = mod;
		keys[nrkeys].keysym = sym;
		keys[nrkeys].func = view;
		tmparg.ui = tag_mask;
		memcpy((void *)&keys[nrkeys].arg, &tmparg, sizeof(Arg));
		nrkeys++;

		/* toggleview */
		keys = ensure_cap(keys, &keys_cap, nrkeys + 1, sizeof(Key));
		keys[nrkeys].mod = mod | WLR_MODIFIER_CTRL;
		keys[nrkeys].keysym = sym;
		keys[nrkeys].func = toggleview;
		tmparg.ui = tag_mask;
		memcpy((void *)&keys[nrkeys].arg, &tmparg, sizeof(Arg));
		nrkeys++;

		/* tag */
		keys = ensure_cap(keys, &keys_cap, nrkeys + 1, sizeof(Key));
		keys[nrkeys].mod = mod | WLR_MODIFIER_SHIFT;
		keys[nrkeys].keysym = sym;
		keys[nrkeys].func = tag;
		tmparg.ui = tag_mask;
		memcpy((void *)&keys[nrkeys].arg, &tmparg, sizeof(Arg));
		nrkeys++;

		/* toggletag */
		keys = ensure_cap(keys, &keys_cap, nrkeys + 1, sizeof(Key));
		keys[nrkeys].mod = mod | WLR_MODIFIER_CTRL | WLR_MODIFIER_SHIFT;
		keys[nrkeys].keysym = sym;
		keys[nrkeys].func = toggletag;
		tmparg.ui = tag_mask;
		memcpy((void *)&keys[nrkeys].arg, &tmparg, sizeof(Arg));
		nrkeys++;
	}

	return 0;
}

/* helper: shrink array to actual size */
static void *
shrink_array(void *arr, int *count, int *cap, int size)
{
	if (*count == 0) {
		free(arr);
		*cap = 0;
		return NULL;
	}
	if (*count < *cap) {
		arr = realloc(arr, *count * size);
		*cap = *count;
	}
	return arr;
}

/* Register all ether.* functions in the Lua state */
static void
ether_lua_register(lua_State *L)
{
	static const luaL_Reg ether_funcs[] = {
		{ "color",                   l_ether_color },
		{ "spawn",                   l_ether_spawn },
		{ "sloppy_focus",            l_ether_sloppy_focus },
		{ "bypass_surface_visibility", l_ether_bypass_surface_visibility },
		{ "border_width",            l_ether_border_width },
		{ "border_color",            l_ether_border_color },
		{ "focus_color",             l_ether_focus_color },
		{ "urgent_color",            l_ether_urgent_color },
		{ "root_color",              l_ether_root_color },
		{ "fullscreen_bg",           l_ether_fullscreen_bg },
		{ "log_level",               l_ether_log_level },
		{ "xkb_rules",              l_ether_xkb_rules },
		{ "repeat_rate",             l_ether_repeat_rate },
		{ "repeat_delay",            l_ether_repeat_delay },
		{ "trackpad",                l_ether_trackpad },
		{ "rule",                    l_ether_rule },
		{ "layout",                  l_ether_layout },
		{ "monitor",                 l_ether_monitor },
		{ "key",                     l_ether_key },
		{ "mouse",                   l_ether_mouse },
		{ "tags",                    l_ether_tags },
		{ "tags_with",               l_ether_tags_with },
		{ NULL, NULL },
	};

	luaL_newlib(L, ether_funcs);
	lua_setglobal(L, "ether");
}

/* apply all config-derived settings to the running compositor state */
static void
apply_config(void)
{
	Client *c;
	Monitor *m;

	/* compositor not yet initialized (early call from lua_load_config) */
	if (!dpy)
		return;

	/* apply monitor rules to all existing monitors */
	wl_list_for_each(m, &mons, link) {
		const MonitorRule *r;
		for (r = monrules; r < monrules + nrmonrules; r++) {
			if (!r->name || strstr(m->wlr_output->name, r->name)) {
				struct wlr_output_state state;

				m->mfact = r->mfact;
				m->nmaster = r->nmaster;

				wlr_output_state_init(&state);
				if (r->scale > 0)
					wlr_output_state_set_scale(&state, r->scale);
				wlr_output_state_set_transform(&state, r->rr);
				wlr_output_commit_state(m->wlr_output, &state);
				wlr_output_state_finish(&state);

				if (r->x >= 0 && r->y >= 0) {
					wlr_output_layout_add(output_layout,
							m->wlr_output, r->x, r->y);
					m->m.x = r->x;
					m->m.y = r->y;
				}

				m->lt[0] = r->lt;
				m->lt[1] = (nrlayouts > 1 && r->lt != &layouts[1])
						? &layouts[1] : &layouts[0];
				strncpy(m->ltsymbol, m->lt[m->sellt]->symbol,
						LENGTH(m->ltsymbol) - 1);
				m->ltsymbol[LENGTH(m->ltsymbol) - 1] = '\0';
				break;
			}
		}
	}

	/* apply border width and colors to all clients */
	wl_list_for_each(c, &clients, link) {
		c->bw = c->isfullscreen ? 0 : borderpx;
		if (c == focustop(c->mon))
			client_set_border_color(c, focuscolor);
		else
			client_set_border_color(c, bordercolor);
	}

	/* apply root and fullscreen background colors */
	wlr_scene_rect_set_color(root_bg, rootcolor);
	wl_list_for_each(m, &mons, link)
		wlr_scene_rect_set_color(m->fullscreen_bg, fullscreen_bg);

	/* apply keyboard config (xkb keymap, repeat rate/delay) */
	{
		struct xkb_context *context;
		struct xkb_keymap *keymap;

		context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
		if ((keymap = xkb_keymap_new_from_names(context, &xkb_rules,
					XKB_KEYMAP_COMPILE_NO_FLAGS))) {
			wlr_keyboard_set_keymap(&kb_group->wlr_group->keyboard, keymap);
			xkb_keymap_unref(keymap);
		}
		xkb_context_unref(context);

		wlr_keyboard_set_repeat_info(&kb_group->wlr_group->keyboard,
				repeat_rate, repeat_delay);
	}

	/* apply trackpad/libinput settings to all pointer devices */
	{
		int i;
		for (i = 0; i < nptr_devs; i++)
			createpointer(wlr_pointer_from_input_device(ptr_devs[i].device));
	}

	/* re-arrange all monitors (also resizes clients with new borderpx) */
	wl_list_for_each(m, &mons, link) {
		if (m->wlr_output->enabled)
			arrange(m);
	}

	printstatus();
}

/* free all dynamically allocated config data */
void
free_config(void)
{
	int i;

	free(keys);
	keys = NULL;
	nrkeys = 0;
	keys_cap = 0;

	free(buttons);
	buttons = NULL;
	nrbuttons = 0;
	buttons_cap = 0;

	for (i = 0; i < nrrules; i++) {
		free((char *)rules[i].id);
		free((char *)rules[i].title);
	}
	free(rules);
	rules = NULL;
	nrrules = 0;
	rules_cap = 0;

	for (i = 0; i < nrlayouts; i++)
		free((char *)layouts[i].symbol);
	free(layouts);
	layouts = NULL;
	nrlayouts = 0;
	layouts_cap = 0;

	for (i = 0; i < nrmonrules; i++)
		free((char *)monrules[i].name);
	free(monrules);
	monrules = NULL;
	if (monrule_layout_names) {
		for (i = 0; i < nrmonrules; i++)
			free(monrule_layout_names[i]);
		free(monrule_layout_names);
	}
	monrule_layout_names = NULL;
	nrmonrules = 0;
	monrules_cap = 0;
	monrule_layout_cap = 0;

	/* free xkb rules strings */
	free((char *)xkb_rules.rules);
	free((char *)xkb_rules.model);
	free((char *)xkb_rules.layout);
	free((char *)xkb_rules.variant);
	free((char *)xkb_rules.options);
	memset(&xkb_rules, 0, sizeof(xkb_rules));

	/* free spawn argv allocations */
	for (i = 0; i < nspawn_argv; i++) {
		char **argv = spawn_argv[i];
		int j;
		for (j = 0; argv[j]; j++)
			free(argv[j]);
		free(argv);
	}
	free(spawn_argv);
	spawn_argv = NULL;
	nspawn_argv = 0;
	spawn_argv_cap = 0;
}

/* reload configuration and reapply */
void
reload(const Arg *arg)
{
	Monitor *m;
	char *path;
	(void)arg;

	/* capture layout symbols from monitors BEFORE freeing old config,
	 * since m->lt[]->symbol points into the about-to-be-freed layouts */
	wl_list_for_each(m, &mons, link) {
		strncpy(m->ltsymbol, m->lt[m->sellt]->symbol,
				LENGTH(m->ltsymbol) - 1);
		m->ltsymbol[LENGTH(m->ltsymbol) - 1] = '\0';
	}

	/* free old config */
	free_config();

	/* reload from lua (strdup so lua_load_config can safely update
	 * current_config_path) */
	path = strdup(current_config_path);
	if (lua_load_config(path)) {
		free(path);
		return;
	}
	free(path);

	/* re-link monitor layout pointers: the layouts array was reallocated,
	 * so every monitor's lt[0]/lt[1] are now dangling.  Look them up
	 * by the symbol saved in ltsymbol, falling back to layouts[0]. */
	wl_list_for_each(m, &mons, link) {
		const Layout *lt = find_layout(m->ltsymbol);
		if (!lt) lt = &layouts[0];
		m->lt[0] = lt;
		m->lt[1] = (nrlayouts > 1) ? &layouts[1] : &layouts[0];
	}

	/* apply all config-derived settings to running state */
	apply_config();
}

/* load lua config from file */
int
lua_load_config(const char *path)
{
	lua_State *L;
	char *configdir;
	int status, i;

	/* determine config path */
	if (path) {
		if (current_config_path)
			free(current_config_path);
		current_config_path = strdup(path);
	} else {
		const char *xdg;
		xdg = getenv("XDG_CONFIG_HOME");
		if (!xdg || !xdg[0]) {
			const char *home = getenv("HOME");
			if (!home || !home[0])
				home = ".";
			snprintf(default_config_path, sizeof(default_config_path),
					"%s/.config/ether/config.lua", home);
		} else {
			snprintf(default_config_path, sizeof(default_config_path),
					"%s/ether/config.lua", xdg);
		}
		if (current_config_path)
			free(current_config_path);
		current_config_path = strdup(default_config_path);
	}

	/* set lua path to search in config directory */
	configdir = strdup(current_config_path);
	{
		char *slash = strrchr(configdir, '/');
		if (slash) {
			*slash = '\0';
			/* also look in the same dir as the config file */
		}
	}

	L = luaL_newstate();
	if (!L) {
		free(configdir);
		fprintf(stderr, "ether: failed to create lua state\n");
		return 1;
	}

	luaL_openlibs(L);
	ether_lua_register(L);

	/* set package.path to include config directory */
	{
		char pkgpath[PATH_MAX];
		lua_getglobal(L, "package");
		lua_getfield(L, -1, "path");
		{
			const char *old = lua_tostring(L, -1);
			snprintf(pkgpath, sizeof(pkgpath),
					"%s/?.lua;%s/?/init.lua;%s",
					configdir, configdir, old ? old : "");
			lua_pop(L, 1);
			lua_pushstring(L, "path");
			lua_pushstring(L, pkgpath);
			lua_rawset(L, -3);
		}
		lua_pop(L, 1);
	}
	free(configdir);

	/* load config file */
	status = luaL_dofile(L, current_config_path);
	if (status != LUA_OK) {
		fprintf(stderr, "ether: %s\n", lua_tostring(L, -1));
		/* append a traceback pointing at the offending line, if any */
		luaL_traceback(L, L, NULL, 0);
		if (strlen(lua_tostring(L, -1)) > strlen("stack traceback:\n"))
			fprintf(stderr, "%s\n", lua_tostring(L, -1));
		lua_close(L);
		return 1;
	}

	lua_close(L);

	/* shrink arrays to actual size */
	keys = shrink_array(keys, &nrkeys, &keys_cap, sizeof(Key));
	buttons = shrink_array(buttons, &nrbuttons, &buttons_cap, sizeof(Button));
	rules = shrink_array(rules, &nrrules, &rules_cap, sizeof(Rule));
	layouts = shrink_array(layouts, &nrlayouts, &layouts_cap, sizeof(Layout));
	monrules = shrink_array(monrules, &nrmonrules, &monrules_cap, sizeof(MonitorRule));

	/* ensure at least one layout and one monitor rule exist */
	if (nrlayouts == 0) {
		layouts = calloc(1, sizeof(Layout));
		layouts[0].symbol = strdup("[]=");
		layouts[0].arrange = tile;
		nrlayouts = 1;
	}
	if (nrmonrules == 0) {
		monrules = calloc(1, sizeof(MonitorRule));
		monrules[0].mfact = 0.55f;
		monrules[0].nmaster = 1;
		monrules[0].scale = 1.0f;
		monrules[0].lt = &layouts[0];
		monrules[0].rr = WL_OUTPUT_TRANSFORM_NORMAL;
		monrules[0].x = -1;
		monrules[0].y = -1;
		nrmonrules = 1;
	}

	/* resolve monitor rules whose layout was referenced before being defined */
	for (i = 0; i < nrmonrules; i++) {
		if (monrule_layout_names && monrule_layout_names[i]) {
			monrules[i].lt = find_layout(monrule_layout_names[i]);
			if (!monrules[i].lt && nrlayouts > 0)
				monrules[i].lt = &layouts[0];
			free(monrule_layout_names[i]);
			monrule_layout_names[i] = NULL;
		}
	}
	free(monrule_layout_names);
	monrule_layout_names = NULL;
	monrule_layout_cap = 0;

	/* apply config to running compositor state (no-op if compositor
	 * hasn't been initialized yet) */
	apply_config();

	return 0;
}
