/*
 * c8tile: update cont8nuum live tiles from the command line, over the
 * session bus (org.cont8nuum.Tiles1, served by c8-shell).
 */
#include <gio/gio.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUS_NAME "org.cont8nuum.Tiles"
#define BUS_PATH "/org/cont8nuum/Tiles"
#define BUS_IFACE "org.cont8nuum.Tiles1"

enum {
	EXIT_OK = 0,
	EXIT_ERROR = 1,
	EXIT_USAGE = 2,
	EXIT_UNSUPPORTED = 3,
};

static const char usage[] =
	"Usage: c8tile <command> <tile-id> [arguments]\n"
	"\n"
	"Commands:\n"
	"  update <tile-id> [--tag TAG] FIELD=VALUE...\n"
	"                         show this on the tile. Without a tag it\n"
	"                         replaces everything there; tagged updates\n"
	"                         take turns, and replace the same tag.\n"
	"  remove <tile-id> TAG   drop the update with this tag\n"
	"  badge <tile-id> TEXT   set the badge (empty clears it)\n"
	"  clear <tile-id>        drop every update and the badge\n"
	"  pin <tile-id> --name NAME --exec COMMAND [--icon ICON]\n"
	"      [--color #rrggbb] [--size small|medium|wide|large]\n"
	"                         ask the user to pin a tile of your own, that\n"
	"                         runs COMMAND (an app opened at something:\n"
	"                         a place, a document). Prints pinned or\n"
	"                         'not pinned'; exits 1 if they said no.\n"
	"  unpin <tile-id>        take off a tile made by pin\n"
	"  restart <tile-id>|--all\n"
	"                         start the tile's provider again (after\n"
	"                         installing a new build of it, say)\n"
	"  watch <tile-id>        print what happens to the tile until the\n"
	"                         shell goes away:\n"
	"                           pinned SIZE | unpinned\n"
	"                           visible 0|1\n"
	"                           activated\n"
	"                           restarting\n"
	"\n"
	"Fields (see org.cont8nuum.Tiles1.xml for the whole list):\n"
	"  template=text|block|image|peek|images|stats|calendar|forecast|\n"
	"           imagetext\n"
	"  heading=  text1= .. text6=  block=  meter=0..100  image=PATH\n"
	"  value1= .. value4=  color=#rrggbb  label=  expires=SECONDS\n"
	"  starts=SECONDS (wait, then show; expires counts from then)\n"
	"  wide.FIELD= (or medium., large.) for one size only\n"
	"\n"
	"Example:\n"
	"  c8tile update mail --tag inbox template=block block=3 \\\n"
	"      text1='new messages' text2='From: alice'\n"
	"\n"
	"Exit status: 0 on success, 1 on errors, 2 on usage errors,\n"
	"3 if no shell serves live tiles.\n";

static GDBusConnection *bus;

static int fail_usage(const char *msg, const char *arg) {
	fprintf(stderr, "c8tile: ");
	fprintf(stderr, msg, arg);
	fprintf(stderr, "\nTry 'c8tile --help' for more information.\n");
	return EXIT_USAGE;
}

static int call(const char *method, GVariant *params) {
	GError *err = NULL;
	GVariant *r = g_dbus_connection_call_sync(bus, BUS_NAME, BUS_PATH,
		BUS_IFACE, method, params, NULL, G_DBUS_CALL_FLAGS_NONE, 5000, NULL,
		&err);
	if (r == NULL) {
		bool missing = g_error_matches(err, G_DBUS_ERROR,
			G_DBUS_ERROR_SERVICE_UNKNOWN) || g_error_matches(err,
			G_DBUS_ERROR, G_DBUS_ERROR_NAME_HAS_NO_OWNER);
		g_dbus_error_strip_remote_error(err);
		fprintf(stderr, "c8tile: %s\n", missing ?
			"no shell serves live tiles here (is c8-shell running?)" :
			err->message);
		g_error_free(err);
		return missing ? EXIT_UNSUPPORTED : EXIT_ERROR;
	}
	g_variant_unref(r);
	return EXIT_OK;
}

static int cmd_update(const char *tile, int argc, char *argv[]) {
	const char *tag = "";
	GVariantBuilder b;
	g_variant_builder_init(&b, G_VARIANT_TYPE("a{ss}"));
	for (int i = 0; i < argc; i++) {
		if (strcmp(argv[i], "--tag") == 0 && i + 1 < argc) {
			tag = argv[++i];
			continue;
		}
		char *eq = strchr(argv[i], '=');
		if (eq == NULL || eq == argv[i]) {
			g_variant_builder_clear(&b);
			return fail_usage("expected FIELD=VALUE, got '%s'", argv[i]);
		}
		char *key = g_strndup(argv[i], eq - argv[i]);
		/* Shells can't easily pass a tab: \t in a value is one */
		GString *value = g_string_new(eq + 1);
		g_string_replace(value, "\\t", "\t", 0);
		g_variant_builder_add(&b, "{ss}", key, value->str);
		g_free(key);
		g_string_free(value, TRUE);
	}
	return call("Update", g_variant_new("(ssa{ss})", tile, tag, &b));
}

/* The user is asked, so it may be a while */
static int cmd_pin(const char *tile, int argc, char *argv[]) {
	static const char *const options[] = { "name", "exec", "icon", "color",
		"size" };
	GVariantBuilder b;
	g_variant_builder_init(&b, G_VARIANT_TYPE("a{ss}"));
	for (int i = 0; i < argc; i++) {
		bool known = false;
		for (size_t k = 0; k < G_N_ELEMENTS(options) && i + 1 < argc; k++) {
			char flag[16];
			snprintf(flag, sizeof(flag), "--%s", options[k]);
			if (strcmp(argv[i], flag) == 0) {
				g_variant_builder_add(&b, "{ss}", options[k], argv[++i]);
				known = true;
				break;
			}
		}
		if (!known) {
			g_variant_builder_clear(&b);
			return fail_usage("unknown or incomplete option '%s'", argv[i]);
		}
	}
	GError *err = NULL;
	GVariant *r = g_dbus_connection_call_sync(bus, BUS_NAME, BUS_PATH,
		BUS_IFACE, "RequestPin", g_variant_new("(sa{ss})", tile, &b),
		G_VARIANT_TYPE("(b)"), G_DBUS_CALL_FLAGS_NONE, 60000, NULL, &err);
	if (r == NULL) {
		g_dbus_error_strip_remote_error(err);
		fprintf(stderr, "c8tile: %s\n", err->message);
		g_error_free(err);
		return EXIT_ERROR;
	}
	gboolean pinned;
	g_variant_get(r, "(b)", &pinned);
	g_variant_unref(r);
	puts(pinned ? "pinned" : "not pinned");
	return pinned ? EXIT_OK : EXIT_ERROR;
}

static GMainLoop *loop;

static void on_signal(GDBusConnection *conn, const char *sender,
		const char *path, const char *iface, const char *signal,
		GVariant *params, gpointer data) {
	const char *tile = data;
	if (strcmp(signal, "TileChanged") == 0) {
		const char *id, *size;
		gboolean pinned;
		g_variant_get(params, "(&sb&s)", &id, &pinned, &size);
		if (strcmp(id, tile) == 0) {
			if (pinned) {
				printf("pinned %s\n", size);
			} else {
				printf("unpinned\n");
			}
		}
	} else if (strcmp(signal, "Activated") == 0 ||
			strcmp(signal, "Restarting") == 0) {
		const char *id;
		g_variant_get(params, "(&s)", &id);
		if (strcmp(id, tile) == 0) {
			printf("%s\n", signal[0] == 'A' ? "activated" : "restarting");
		}
	} else if (strcmp(signal, "PropertiesChanged") == 0) {
		GVariant *changed = g_variant_get_child_value(params, 1);
		gboolean visible;
		if (g_variant_lookup(changed, "StartVisible", "b", &visible)) {
			printf("visible %d\n", visible);
		}
		g_variant_unref(changed);
	}
	fflush(stdout);
}

static void vanished(GDBusConnection *conn, const char *name, gpointer data) {
	g_main_loop_quit(loop);
}

static int cmd_watch(const char *tile) {
	GError *err = NULL;
	GVariant *r = g_dbus_connection_call_sync(bus, BUS_NAME, BUS_PATH,
		BUS_IFACE, "GetTile", g_variant_new("(s)", tile), G_VARIANT_TYPE("(bs)"),
		G_DBUS_CALL_FLAGS_NONE, 5000, NULL, &err);
	if (r == NULL) {
		fprintf(stderr, "c8tile: %s\n", err->message);
		g_error_free(err);
		return EXIT_UNSUPPORTED;
	}
	gboolean pinned;
	const char *size;
	g_variant_get(r, "(b&s)", &pinned, &size);
	if (pinned) {
		printf("pinned %s\n", size);
	} else {
		printf("unpinned\n");
	}
	g_variant_unref(r);
	r = g_dbus_connection_call_sync(bus, BUS_NAME, BUS_PATH,
		"org.freedesktop.DBus.Properties", "Get",
		g_variant_new("(ss)", BUS_IFACE, "StartVisible"), G_VARIANT_TYPE("(v)"),
		G_DBUS_CALL_FLAGS_NONE, 5000, NULL, NULL);
	if (r) {
		GVariant *v;
		g_variant_get(r, "(v)", &v);
		printf("visible %d\n", g_variant_get_boolean(v));
		g_variant_unref(v);
		g_variant_unref(r);
	}
	fflush(stdout);

	loop = g_main_loop_new(NULL, FALSE);
	g_dbus_connection_signal_subscribe(bus, BUS_NAME, BUS_IFACE, NULL,
		BUS_PATH, NULL, G_DBUS_SIGNAL_FLAGS_NONE, on_signal, (void *)tile,
		NULL);
	g_dbus_connection_signal_subscribe(bus, BUS_NAME,
		"org.freedesktop.DBus.Properties", "PropertiesChanged", BUS_PATH,
		BUS_IFACE, G_DBUS_SIGNAL_FLAGS_NONE, on_signal, (void *)tile, NULL);
	g_bus_watch_name_on_connection(bus, BUS_NAME,
		G_BUS_NAME_WATCHER_FLAGS_NONE, NULL, vanished, NULL, NULL);
	g_main_loop_run(loop);
	return EXIT_ERROR; // the shell went away
}

int main(int argc, char *argv[]) {
	for (int i = 1; i < argc; i++) {
		if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) {
			fputs(usage, stdout);
			return EXIT_OK;
		}
	}
	if (argc < 3) {
		fputs(usage, stderr);
		return EXIT_USAGE;
	}
	const char *cmd = argv[1], *tile = argv[2];
	if (tile[0] == '\0') {
		return fail_usage("the tile id is empty%s", "");
	}
	GError *err = NULL;
	bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, &err);
	if (bus == NULL) {
		fprintf(stderr, "c8tile: no session bus: %s\n", err->message);
		g_error_free(err);
		return EXIT_ERROR;
	}
	if (strcmp(cmd, "update") == 0) {
		return cmd_update(tile, argc - 3, argv + 3);
	} else if (strcmp(cmd, "remove") == 0 && argc == 4) {
		return call("Remove", g_variant_new("(ss)", tile, argv[3]));
	} else if (strcmp(cmd, "pin") == 0) {
		return cmd_pin(tile, argc - 3, argv + 3);
	} else if (strcmp(cmd, "unpin") == 0 && argc == 3) {
		return call("Unpin", g_variant_new("(s)", tile));
	} else if (strcmp(cmd, "badge") == 0 && argc == 4) {
		return call("SetBadge", g_variant_new("(ss)", tile, argv[3]));
	} else if (strcmp(cmd, "clear") == 0 && argc == 3) {
		return call("Clear", g_variant_new("(s)", tile));
	} else if (strcmp(cmd, "restart") == 0 && argc == 3) {
		return call("Restart", g_variant_new("(s)",
			strcmp(tile, "--all") == 0 ? "" : tile));
	} else if (strcmp(cmd, "watch") == 0 && argc == 3) {
		return cmd_watch(tile);
	}
	return fail_usage("unknown command or wrong arguments: '%s'", cmd);
}
