/*
 * Wake-ups (org.cont8nuum.Wake1, documented in c8-protocols): apps book a
 * time, and the shell starts them then for a moment, so nothing of them
 * runs in between. The list is a key file in the state dir; a group a
 * wake, named "APP TAG".
 *
 * Only the shell that owns the name runs wakes: a second shell on the
 * same bus (nested, say) would otherwise run each one twice.
 */
#include <errno.h>
#include <gio/gio.h>
#include <stdio.h>
#include <string.h>
#include "shell.h"
#include "wake-info.h"

#define BUS_NAME "org.cont8nuum.Wake"
#define BUS_PATH "/org/cont8nuum/Wake"
#define MAX_PER_APP 32
#define MIN_EVERY 60
#define LOOK_EVERY 60 // s: the longest the shell sleeps, for suspends

static struct {
	GKeyFile *list;
	char *path;
	bool owner;
	guint timer;
} wk;

static void arm(void);

static void save(void) {
	char *dir = g_path_get_dirname(wk.path);
	g_mkdir_with_parents(dir, 0700);
	g_free(dir);
	GError *err = NULL;
	if (!g_key_file_save_to_file(wk.list, wk.path, &err)) {
		fprintf(stderr, "c8-shell: can't keep the wakes: %s\n", err->message);
		g_error_free(err);
	}
}

static bool good_tag(const char *tag) {
	size_t n = strlen(tag);
	if (n == 0 || n > 64) {
		return false;
	}
	for (const char *p = tag; *p; p++) {
		if (!g_ascii_isalnum(*p) && !strchr("-_.", *p)) {
			return false;
		}
	}
	return true;
}

static char *group_of(const char *app, const char *tag) {
	return g_strdup_printf("%s %s", app, tag);
}

/* The app of a group, its first word: borrowed until the next call */
static const char *app_of(const char *group, char **tag) {
	static char app[256];
	const char *space = strchr(group, ' ');
	size_t n = space ? (size_t)(space - group) : strlen(group);
	n = MIN(n, sizeof(app) - 1);
	memcpy(app, group, n);
	app[n] = '\0';
	if (tag) {
		*tag = space ? (char *)space + 1 : (char *)"";
	}
	return app;
}

static int count_for(const char *app) {
	int n = 0;
	char **groups = g_key_file_get_groups(wk.list, NULL);
	for (int i = 0; groups[i]; i++) {
		if (strcmp(app_of(groups[i], NULL), app) == 0) {
			n++;
		}
	}
	g_strfreev(groups);
	return n;
}

/* Runs one through the compositor, as Start runs an app, so it gets the
 * session's environment; no splash comes with it */
static void run(const char *group, const char *tag, gint64 due) {
	gsize n = 0;
	char **command = g_key_file_get_string_list(wk.list, group, "command",
		&n, NULL);
	if (command == NULL || n == 0) {
		g_strfreev(command);
		return;
	}
	GString *line = g_string_new(NULL);
	for (gsize i = 0; i < n; i++) {
		char *q = g_shell_quote(command[i]);
		g_string_append_printf(line, "%s%s", i ? " " : "", q);
		g_free(q);
	}
	char *q = g_shell_quote(tag);
	g_string_append_printf(line, " --c8-wake %s %" G_GINT64_FORMAT, q, due);
	g_free(q);
	c8_shell_v1_launch(shell.proto, line->str);
	g_string_free(line, TRUE);
	g_strfreev(command);
}

/* Runs what is due, then sleeps until the next one (or a minute) */
static gboolean tick(gpointer data) {
	wk.timer = 0;
	if (!wk.owner) {
		return G_SOURCE_REMOVE;
	}
	gint64 now = g_get_real_time() / G_USEC_PER_SEC;
	bool changed = false;
	char **groups = g_key_file_get_groups(wk.list, NULL);
	for (int i = 0; groups[i]; i++) {
		gint64 when = g_key_file_get_int64(wk.list, groups[i], "when", NULL);
		if (when > now) {
			continue;
		}
		char *tag;
		app_of(groups[i], &tag);
		char *tag_copy = g_strdup(tag);
		run(groups[i], tag_copy, when);
		g_free(tag_copy);
		gint64 every = g_key_file_get_int64(wk.list, groups[i], "every", NULL);
		if (every > 0) {
			/* Missed ones are run once, not each */
			gint64 next = when + ((now - when) / every + 1) * every;
			g_key_file_set_int64(wk.list, groups[i], "when", next);
		} else {
			g_key_file_remove_group(wk.list, groups[i], NULL);
		}
		changed = true;
	}
	g_strfreev(groups);
	if (changed) {
		save();
	}
	arm();
	return G_SOURCE_REMOVE;
}

static void arm(void) {
	if (wk.timer) {
		g_source_remove(wk.timer);
		wk.timer = 0;
	}
	if (!wk.owner) {
		return;
	}
	gint64 now = g_get_real_time() / G_USEC_PER_SEC;
	gint64 next = -1;
	char **groups = g_key_file_get_groups(wk.list, NULL);
	for (int i = 0; groups[i]; i++) {
		gint64 when = g_key_file_get_int64(wk.list, groups[i], "when", NULL);
		if (next < 0 || when < next) {
			next = when;
		}
	}
	g_strfreev(groups);
	if (next < 0) {
		return; // nothing booked: nothing to look at
	}
	/* The main loop's clock stops in a suspend and the wall clock doesn't,
	 * so never sleep long on it */
	gint64 wait = CLAMP(next - now, 0, LOOK_EVERY);
	wk.timer = wait == 0 ? g_idle_add(tick, NULL) :
		g_timeout_add_seconds((guint)wait, tick, NULL);
}

static void method_call(GDBusConnection *conn, const char *sender,
		const char *path, const char *iface, const char *method,
		GVariant *params, GDBusMethodInvocation *inv, gpointer data) {
	if (strcmp(method, "Set") == 0) {
		const char *app, *tag;
		gint64 when;
		guint32 every;
		char **command;
		g_variant_get(params, "(&s&sxu^as)", &app, &tag, &when, &every,
			&command);
		const char *bad = NULL;
		char *group = group_of(app, tag);
		if (!g_dbus_is_name(app) || g_dbus_is_unique_name(app) ||
				strchr(app, ' ')) {
			bad = "The app is its id, like org.example.Notes";
		} else if (!good_tag(tag)) {
			bad = "A tag is up to 64 letters, digits, '-', '_' and '.'";
		} else if (every != 0 && every < MIN_EVERY) {
			bad = "A repeating wake is at least 60 seconds apart";
		} else if (command[0] == NULL || command[0][0] == '\0') {
			bad = "There is no command";
		} else if (!g_key_file_has_group(wk.list, group) &&
				count_for(app) >= MAX_PER_APP) {
			bad = "That app has 32 wakes already";
		}
		if (bad) {
			g_dbus_method_invocation_return_error_literal(inv, G_DBUS_ERROR,
				G_DBUS_ERROR_INVALID_ARGS, bad);
		} else {
			g_key_file_set_int64(wk.list, group, "when", when);
			g_key_file_set_int64(wk.list, group, "every", every);
			g_key_file_set_string_list(wk.list, group, "command",
				(const char *const *)command, g_strv_length(command));
			save();
			arm();
			g_dbus_method_invocation_return_value(inv, NULL);
		}
		g_free(group);
		g_strfreev(command);
	} else if (strcmp(method, "Cancel") == 0) {
		const char *app, *tag;
		g_variant_get(params, "(&s&s)", &app, &tag);
		char *group = group_of(app, tag);
		if (g_key_file_remove_group(wk.list, group, NULL)) {
			save();
			arm();
		}
		g_free(group);
		g_dbus_method_invocation_return_value(inv, NULL);
	} else if (strcmp(method, "List") == 0) {
		const char *app;
		g_variant_get(params, "(&s)", &app);
		GVariantBuilder b;
		g_variant_builder_init(&b, G_VARIANT_TYPE("a(sxu)"));
		char **groups = g_key_file_get_groups(wk.list, NULL);
		for (int i = 0; groups[i]; i++) {
			char *tag;
			if (strcmp(app_of(groups[i], &tag), app) != 0) {
				continue;
			}
			g_variant_builder_add(&b, "(sxu)", tag,
				g_key_file_get_int64(wk.list, groups[i], "when", NULL),
				(guint32)g_key_file_get_int64(wk.list, groups[i], "every",
					NULL));
		}
		g_strfreev(groups);
		g_dbus_method_invocation_return_value(inv,
			g_variant_new("(a(sxu))", &b));
	} else {
		g_dbus_method_invocation_return_error(inv, G_DBUS_ERROR,
			G_DBUS_ERROR_UNKNOWN_METHOD, "No method %s", method);
	}
}

static const GDBusInterfaceVTable vtable = { .method_call = method_call };

static void bus_acquired(GDBusConnection *bus, const char *name,
		gpointer data) {
	GError *err = NULL;
	if (!g_dbus_connection_register_object(bus, BUS_PATH,
			(GDBusInterfaceInfo *)&org_cont8nuum_wake1_interface, &vtable,
			NULL, NULL, &err)) {
		fprintf(stderr, "c8-shell: cannot serve wakes: %s\n", err->message);
		g_error_free(err);
	}
}

static void name_acquired(GDBusConnection *bus, const char *name,
		gpointer data) {
	wk.owner = true;
	/* Another shell may have changed the list while it had the name */
	g_key_file_load_from_file(wk.list, wk.path, G_KEY_FILE_NONE, NULL);
	arm();
}

static void name_lost(GDBusConnection *bus, const char *name, gpointer data) {
	wk.owner = false;
	arm();
}

void wake_init(void) {
	wk.list = g_key_file_new();
	wk.path = g_build_filename(g_get_user_state_dir(), "cont8nuum",
		"wakes.ini", NULL);
	GError *err = NULL;
	if (!g_key_file_load_from_file(wk.list, wk.path, G_KEY_FILE_NONE, &err)) {
		if (!g_error_matches(err, G_FILE_ERROR, G_FILE_ERROR_NOENT)) {
			fprintf(stderr, "c8-shell: can't read %s: %s\n", wk.path,
				err->message);
		}
		g_error_free(err);
	}
	/* The newest shell wins, as with live tiles */
	g_bus_own_name(G_BUS_TYPE_SESSION, BUS_NAME,
		G_BUS_NAME_OWNER_FLAGS_ALLOW_REPLACEMENT |
		G_BUS_NAME_OWNER_FLAGS_REPLACE, bus_acquired, name_acquired, name_lost,
		NULL, NULL);
}
