/*
 * One copy per app: c8ui_app_main owns the app id on the session bus and
 * serves org.freedesktop.Application there. A second launch finds the
 * name taken, hands its files over with Open (or Activate) and exits;
 * the activation token it was launched with goes along, so the running
 * copy may bring its window forward.
 *
 * Wake-ups (org.cont8nuum.Wake1): the shell runs the app's command with
 * --c8-wake TAG DUE. With a copy running, that is handed over as the
 * action "c8-wake"; without, the app runs windowless on a hold that
 * c8ui_app_wake_done (or C8UI_WAKE_SECONDS) lets go.
 *
 * Also opening a URI in another app, with a token of ours.
 */
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gio/gio.h>
#include "c8ui-wayland.h"
#include "wayland-private.h"

#define IFACE "org.freedesktop.Application"
#define FORWARD_TIMEOUT 10000 // ms the running copy has to answer
#define WAKE_NAME "org.cont8nuum.Wake"
#define WAKE_PATH "/org/cont8nuum/Wake"
#define WAKE_IFACE "org.cont8nuum.Wake1"

static const char introspection[] =
	"<node><interface name='org.freedesktop.Application'>"
	"<method name='Activate'>"
	"<arg name='platform_data' type='a{sv}' direction='in'/></method>"
	"<method name='Open'><arg name='uris' type='as' direction='in'/>"
	"<arg name='platform_data' type='a{sv}' direction='in'/></method>"
	"<method name='ActivateAction'>"
	"<arg name='action_name' type='s' direction='in'/>"
	"<arg name='parameter' type='av' direction='in'/>"
	"<arg name='platform_data' type='a{sv}' direction='in'/></method>"
	"</interface></node>";

struct running {
	const struct c8ui_app_info *info;
	struct c8ui_app *app; // NULL until the first open
	char **command; // what the shell runs for a wake
	bool waking; // started for a wake: holding the app until it's done
	guint wake_timer;
};

/* The one app of c8ui_app_main, for the wake calls */
static struct running *current;

/* org.example.App → /org/example/App, as the spec has it */
static char *object_path(const char *id) {
	char *path = g_strdup_printf("/%s", id);
	for (char *p = path; *p; p++) {
		if (*p == '.') {
			*p = '/';
		} else if (*p == '-') {
			*p = '_';
		}
	}
	return path;
}

static const char *token_from(GVariant *platform_data) {
	const char *token = NULL;
	if (!g_variant_lookup(platform_data, "activation-token", "&s", &token)) {
		g_variant_lookup(platform_data, "desktop-startup-id", "&s", &token);
	}
	return token;
}

static void open_with(struct running *r, char **uris, const char *token) {
	c8ui_app_set_launch_token(r->app, token);
	r->info->open(r->app, uris, r->info->data);
	c8ui_app_set_launch_token(r->app, NULL); // unused: never later
}

/* The value in the i-th variant of an av */
static GVariant *arg_at(GVariant *av, gsize i) {
	GVariant *boxed = g_variant_get_child_value(av, i);
	GVariant *value = g_variant_get_variant(boxed);
	g_variant_unref(boxed);
	return value;
}

static void wake_with(struct running *r, const char *tag, gint64 due) {
	if (r->info->wake) {
		r->info->wake(r->app, tag, due, r->info->data);
	} else {
		c8ui_app_wake_done(r->app); // nothing to wait for
	}
}

static void method_call(GDBusConnection *conn, const char *sender,
		const char *path, const char *iface, const char *method,
		GVariant *params, GDBusMethodInvocation *inv, gpointer data) {
	struct running *r = data;
	if (r->app == NULL) {
		g_dbus_method_invocation_return_error(inv, G_DBUS_ERROR,
			G_DBUS_ERROR_FAILED, "Still starting");
		return;
	}
	if (strcmp(method, "Activate") == 0) {
		GVariant *pd = g_variant_get_child_value(params, 0);
		char *none[] = { NULL };
		g_dbus_method_invocation_return_value(inv, NULL);
		open_with(r, none, token_from(pd));
		g_variant_unref(pd);
	} else if (strcmp(method, "Open") == 0) {
		char **uris;
		GVariant *pd;
		g_variant_get(params, "(^as@a{sv})", &uris, &pd);
		g_dbus_method_invocation_return_value(inv, NULL);
		open_with(r, uris, token_from(pd));
		g_strfreev(uris);
		g_variant_unref(pd);
	} else if (strcmp(method, "ActivateAction") == 0 &&
			g_variant_is_of_type(params, G_VARIANT_TYPE("(sava{sv})"))) {
		const char *action;
		GVariant *args;
		g_variant_get(params, "(&s@av@a{sv})", &action, &args, NULL);
		GVariant *tag = NULL, *due = NULL;
		if (strcmp(action, "c8-wake") == 0 && g_variant_n_children(args) == 2) {
			tag = arg_at(args, 0);
			due = arg_at(args, 1);
		}
		if (tag && due && g_variant_is_of_type(tag, G_VARIANT_TYPE_STRING) &&
				g_variant_is_of_type(due, G_VARIANT_TYPE_INT64)) {
			g_dbus_method_invocation_return_value(inv, NULL);
			wake_with(r, g_variant_get_string(tag, NULL),
				g_variant_get_int64(due));
		} else {
			g_dbus_method_invocation_return_error(inv, G_DBUS_ERROR,
				G_DBUS_ERROR_NOT_SUPPORTED, "No action %s", action);
		}
		if (tag) {
			g_variant_unref(tag);
		}
		if (due) {
			g_variant_unref(due);
		}
		g_variant_unref(args);
	} else {
		/* No other actions: nothing in a .desktop file names any */
		g_dbus_method_invocation_return_error(inv, G_DBUS_ERROR,
			G_DBUS_ERROR_NOT_SUPPORTED, "No actions");
	}
}

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

/* argv's files and URIs as URIs, made absolute here since the running
 * copy has another working directory */
static char **uris_from_args(const char *id, int argc, char **argv) {
	GPtrArray *uris = g_ptr_array_new();
	bool options = true;
	for (int i = 1; i < argc; i++) {
		const char *arg = argv[i];
		if (options && strcmp(arg, "--") == 0) {
			options = false;
			continue;
		}
		if (options && arg[0] == '-' && arg[1] != '\0') {
			fprintf(stderr, "%s: unknown option %s\n", id, arg);
			g_ptr_array_free(uris, TRUE);
			return NULL;
		}
		/* A URI goes as it is: GIO's dummy GFile for a scheme it doesn't
		 * know reads the authority as host:port, which made
		 * at://did:plc:… into at://did:0/… */
		const char *scheme = g_uri_peek_scheme(arg); // interned
		if (scheme && strcmp(scheme, "file") != 0) {
			g_ptr_array_add(uris, g_strdup(arg));
			continue;
		}
		GFile *file = g_file_new_for_commandline_arg(arg);
		g_ptr_array_add(uris, g_file_get_uri(file));
		g_object_unref(file);
	}
	g_ptr_array_add(uris, NULL);
	return (char **)g_ptr_array_free(uris, FALSE);
}

/* Takes "--c8-wake TAG DUE" out of argv: true if it was there (tag is
 * then the TAG, an argv string) */
static bool wake_from_args(int *argc, char **argv, const char **tag,
		gint64 *due) {
	for (int i = 1; i < *argc; i++) {
		if (strcmp(argv[i], "--") == 0) {
			return false;
		}
		if (strcmp(argv[i], "--c8-wake") == 0 && i + 2 < *argc) {
			*tag = argv[i + 1];
			*due = g_ascii_strtoll(argv[i + 2], NULL, 10);
			memmove(argv + i, argv + i + 3,
				(size_t)(*argc - i - 3 + 1) * sizeof(*argv));
			*argc -= 3;
			return true;
		}
	}
	return false;
}

/* What the shell is to run for a wake: the info's, else this program */
static char **wake_command(const struct c8ui_app_info *info) {
	if (info->command && info->command[0]) {
		return g_strdupv((char **)info->command);
	}
	char *self = g_file_read_link("/proc/self/exe", NULL);
	char *one[] = { self ? self : "", NULL };
	char **command = g_strdupv(one);
	g_free(self);
	return command;
}

static int forward_wake(GDBusConnection *bus, const char *id,
		const char *path, const char *tag, gint64 due) {
	GVariant *args[] = { g_variant_new_variant(g_variant_new_string(tag)),
		g_variant_new_variant(g_variant_new_int64(due)) };
	GError *error = NULL;
	GVariant *reply = g_dbus_connection_call_sync(bus, id, path, IFACE,
		"ActivateAction", g_variant_new("(s@ava{sv})", "c8-wake",
			g_variant_new_array(G_VARIANT_TYPE_VARIANT, args, 2), NULL),
		NULL, G_DBUS_CALL_FLAGS_NO_AUTO_START, FORWARD_TIMEOUT, NULL, &error);
	if (reply == NULL) {
		fprintf(stderr, "%s: the copy already running didn't take the "
			"wake: %s\n", id, error->message);
		g_error_free(error);
		return EXIT_FAILURE;
	}
	g_variant_unref(reply);
	return EXIT_SUCCESS;
}

static gboolean wake_over(gpointer data) {
	struct running *r = data;
	r->wake_timer = 0;
	c8ui_app_wake_done(r->app);
	return G_SOURCE_REMOVE;
}

void c8ui_app_wake_done(struct c8ui_app *app) {
	struct running *r = current;
	if (r == NULL || r->app != app || !r->waking) {
		return;
	}
	r->waking = false;
	if (r->wake_timer) {
		g_source_remove(r->wake_timer);
		r->wake_timer = 0;
	}
	c8ui_app_release(app);
}

static void wake_answered(GObject *source, GAsyncResult *result,
		gpointer data) {
	GError *error = NULL;
	GVariant *reply = g_dbus_connection_call_finish(G_DBUS_CONNECTION(source),
		result, &error);
	if (reply) {
		g_variant_unref(reply);
	} else {
		fprintf(stderr, "c8ui: the shell didn't take the wake: %s\n",
			error->message);
		g_error_free(error);
	}
}

static void wake_call(const char *method, GVariant *params) {
	GDBusConnection *bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, NULL);
	if (bus == NULL) {
		g_variant_unref(g_variant_ref_sink(params));
		return;
	}
	/* Answered or not before the app quits, the call has gone: the bus
	 * is flushed on the way out */
	g_dbus_connection_call(bus, WAKE_NAME, WAKE_PATH, WAKE_IFACE, method,
		params, NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, wake_answered, NULL);
	g_object_unref(bus);
}

void c8ui_app_wake_at(struct c8ui_app *app, const char *tag, int64_t when,
		unsigned every) {
	struct running *r = current;
	if (r == NULL || r->app != app) {
		fprintf(stderr, "c8ui: wakes are for apps of c8ui_app_main\n");
		return;
	}
	wake_call("Set", g_variant_new("(ssxu^as)", r->info->id, tag,
		(gint64)when, (guint32)every, r->command));
}

void c8ui_app_wake_cancel(struct c8ui_app *app, const char *tag) {
	struct running *r = current;
	if (r == NULL || r->app != app) {
		return;
	}
	wake_call("Cancel", g_variant_new("(ss)", r->info->id, tag));
}

static int forward(GDBusConnection *bus, const char *id, const char *path,
		char **uris, const char *token) {
	GVariantBuilder pd;
	g_variant_builder_init(&pd, G_VARIANT_TYPE_VARDICT);
	if (token) {
		g_variant_builder_add(&pd, "{sv}", "activation-token",
			g_variant_new_string(token));
		g_variant_builder_add(&pd, "{sv}", "desktop-startup-id",
			g_variant_new_string(token));
	}
	GVariant *params = uris[0] ?
		g_variant_new("(^asa{sv})", uris, &pd) :
		g_variant_new("(a{sv})", &pd);
	GError *error = NULL;
	GVariant *reply = g_dbus_connection_call_sync(bus, id, path, IFACE,
		uris[0] ? "Open" : "Activate", params, NULL,
		G_DBUS_CALL_FLAGS_NO_AUTO_START, FORWARD_TIMEOUT, NULL, &error);
	if (reply == NULL) {
		fprintf(stderr, "%s: the copy already running didn't answer: %s\n",
			id, error->message);
		g_error_free(error);
		return EXIT_FAILURE;
	}
	g_variant_unref(reply);
	return EXIT_SUCCESS;
}

int c8ui_app_main(const struct c8ui_app_info *info, int argc, char **argv) {
	const char *id = info->id;
	if (!g_dbus_is_name(id) || g_dbus_is_unique_name(id)) {
		fprintf(stderr, "%s: the app id must be like org.example.App\n", id);
		return EXIT_FAILURE;
	}
	const char *wake_tag = NULL;
	gint64 wake_due = 0;
	bool waking = wake_from_args(&argc, argv, &wake_tag, &wake_due);
	char **uris = uris_from_args(id, argc, argv);
	if (uris == NULL) {
		return 2;
	}
	/* Ours to use, not for whatever we launch */
	char *token = g_strdup(g_getenv("XDG_ACTIVATION_TOKEN"));
	g_unsetenv("XDG_ACTIVATION_TOKEN");
	g_unsetenv("DESKTOP_STARTUP_ID");

	struct running r = { .info = info, .command = wake_command(info) };
	current = &r;
	char *path = object_path(id);
	guint object = 0;
	int status = EXIT_SUCCESS;
	GError *error = NULL;
	GDBusConnection *bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, &error);
	if (bus == NULL) {
		/* Still usable, just not as the one copy */
		fprintf(stderr, "%s: no session bus: %s\n", id, error->message);
		g_clear_error(&error);
	} else {
		/* Served before the name is taken, so nobody can call too early */
		GDBusNodeInfo *node = g_dbus_node_info_new_for_xml(introspection, NULL);
		object = g_dbus_connection_register_object(bus, path,
			node->interfaces[0], &vtable, &r, NULL, &error);
		g_dbus_node_info_unref(node);
		if (object == 0) {
			fprintf(stderr, "%s: %s\n", id, error->message);
			g_clear_error(&error);
		}
		GVariant *reply = g_dbus_connection_call_sync(bus,
			"org.freedesktop.DBus", "/org/freedesktop/DBus",
			"org.freedesktop.DBus", "RequestName",
			g_variant_new("(su)", id, 4 /* DO_NOT_QUEUE */),
			G_VARIANT_TYPE("(u)"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
		guint32 result = 0;
		if (reply) {
			g_variant_get(reply, "(u)", &result);
			g_variant_unref(reply);
		} else {
			fprintf(stderr, "%s: %s\n", id, error->message);
			g_clear_error(&error);
		}
		if (result == 3 /* EXISTS */) {
			status = waking ?
				forward_wake(bus, id, path, wake_tag, wake_due) :
				forward(bus, id, path, uris, token);
			goto out;
		}
	}

	r.app = c8ui_app_new(id);
	if (r.app == NULL) {
		status = EXIT_FAILURE;
		goto out;
	}
	if (bus) {
		c8ui_app_set_unique_bus(r.app, bus);
	}
	if (info->startup) {
		info->startup(r.app, info->data);
	}
	if (waking) {
		/* No window: held until the wake is done, or for its time */
		r.waking = true;
		c8ui_app_hold(r.app);
		r.wake_timer = g_timeout_add_seconds(C8UI_WAKE_SECONDS, wake_over, &r);
		wake_with(&r, wake_tag, wake_due);
	} else {
		open_with(&r, uris, token);
	}
	/* Nothing to show (it only printed something, say): done */
	if (c8ui_app_has_windows(r.app)) {
		status = c8ui_app_run(r.app);
	}
	if (info->shutdown) {
		info->shutdown(r.app, info->data);
	}
	if (r.wake_timer) {
		g_source_remove(r.wake_timer);
	}
	struct c8ui_app *app = r.app;
	r.app = NULL; // calls now say "still starting" until the bus goes
	c8ui_app_destroy(app);

out:
	if (object) {
		g_dbus_connection_unregister_object(bus, object);
	}
	if (bus) {
		g_dbus_connection_flush_sync(bus, NULL, NULL);
		g_object_unref(bus);
	}
	g_free(path);
	g_free(token);
	g_strfreev(uris);
	g_strfreev(r.command);
	current = NULL;
	return status;
}

/* Opening a URI in another app. GIO picks the app; a launch context of
 * ours gives it our token (as XDG_ACTIVATION_TOKEN, or in the platform
 * data of a D-Bus activated app). */

typedef struct {
	GAppLaunchContext parent;
	char *token;
} C8uiLaunchContext;

typedef struct {
	GAppLaunchContextClass parent;
} C8uiLaunchContextClass;

GType c8ui_launch_context_get_type(void);
G_DEFINE_TYPE(C8uiLaunchContext, c8ui_launch_context, G_TYPE_APP_LAUNCH_CONTEXT)

static char *launch_token(GAppLaunchContext *context, GAppInfo *info,
		GList *files) {
	C8uiLaunchContext *self = (C8uiLaunchContext *)context;
	return g_strdup(self->token);
}

static void launch_finalize(GObject *object) {
	g_free(((C8uiLaunchContext *)object)->token);
	G_OBJECT_CLASS(c8ui_launch_context_parent_class)->finalize(object);
}

static void c8ui_launch_context_class_init(C8uiLaunchContextClass *class) {
	G_OBJECT_CLASS(class)->finalize = launch_finalize;
	G_APP_LAUNCH_CONTEXT_CLASS(class)->get_startup_notify_id = launch_token;
}

static void c8ui_launch_context_init(C8uiLaunchContext *self) {
}

static void launched(GObject *source, GAsyncResult *result, gpointer data) {
	char *uri = data;
	GError *error = NULL;
	if (!g_app_info_launch_default_for_uri_finish(result, &error)) {
		fprintf(stderr, "c8ui: can't open %s: %s\n", uri, error->message);
		g_error_free(error);
	}
	g_free(uri);
}

static void open_uri_with(const char *token, void *data) {
	char *uri = data;
	C8uiLaunchContext *context =
		g_object_new(c8ui_launch_context_get_type(), NULL);
	context->token = g_strdup(token);
	g_app_info_launch_default_for_uri_async(uri, G_APP_LAUNCH_CONTEXT(context),
		NULL, launched, uri);
	g_object_unref(context);
}

void c8ui_window_open_uri(struct c8ui_window *win, const char *uri) {
	c8ui_window_request_token(win, open_uri_with, g_strdup(uri));
}

struct launch {
	char *id;
	GList *uris; // char *
};

static void app_launched(GObject *source, GAsyncResult *result, gpointer data) {
	GError *error = NULL;
	if (!g_app_info_launch_uris_finish(G_APP_INFO(source), result, &error)) {
		fprintf(stderr, "c8ui: can't start %s: %s\n",
			g_app_info_get_id(G_APP_INFO(source)), error->message);
		g_error_free(error);
	}
}

static void launch_with(const char *token, void *data) {
	struct launch *l = data;
	GAppInfo *info = NULL;
	GList *all = g_app_info_get_all();
	for (GList *a = all; a && info == NULL; a = a->next) {
		const char *id = g_app_info_get_id(a->data);
		if (id && strcmp(id, l->id) == 0) {
			info = g_object_ref(a->data);
		}
	}
	g_list_free_full(all, g_object_unref);
	if (info) {
		C8uiLaunchContext *context =
			g_object_new(c8ui_launch_context_get_type(), NULL);
		context->token = g_strdup(token);
		g_app_info_launch_uris_async(info, l->uris,
			G_APP_LAUNCH_CONTEXT(context), NULL, app_launched, NULL);
		g_object_unref(context);
		g_object_unref(info);
	} else {
		fprintf(stderr, "c8ui: no app %s\n", l->id);
	}
	g_free(l->id);
	g_list_free_full(l->uris, g_free);
	g_free(l);
}

void c8ui_window_launch(struct c8ui_window *win, const char *desktop_id,
		const char *const *uris) {
	struct launch *l = g_new0(struct launch, 1);
	l->id = g_strdup(desktop_id);
	for (int i = 0; uris && uris[i]; i++) {
		l->uris = g_list_append(l->uris, g_strdup(uris[i]));
	}
	c8ui_window_request_token(win, launch_with, l);
}
