/*
 * script: a tile from a command's output, for tiles that need no
 * program of their own. A .widget file says it all:
 *
 *   [Widget]
 *   Name=Disk space
 *   Command=df -h --output=pcent / | tail -1
 *   Interval=60
 *   Template=block
 *
 * The command runs through sh every Interval seconds while Start shows
 * (and when it comes up). What it prints is the tile: lines of
 * FIELD=VALUE as c8tile takes them, or plain lines, the first the
 * heading (the block, for the block template) and the rest text1 on.
 */
#include <gio/gio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "stealth.h"
#include "widget.h"

#define TIMEOUT_S 30 // a command that hangs is killed
#define MAX_BYTES 65536

struct script {
	char *command, *template;
	int interval; // seconds
	gint64 last; // monotonic us of the last run, 0: never
	GSubprocess *running;
	guint timeout;
	GHashTable *fields; // what the tile shows
	struct widget *w;
};

static bool field_key(const char *line, const char *eq) {
	if (eq == NULL || eq == line) {
		return false;
	}
	for (const char *p = line; p < eq; p++) {
		if (!g_ascii_islower(*p) && !g_ascii_isdigit(*p) && *p != '.' &&
				*p != '_') {
			return false;
		}
	}
	return true;
}

static void parse(struct script *s, const char *out) {
	char **lines = g_strsplit(out, "\n", 0);
	GHashTable *fields = g_hash_table_new_full(g_str_hash, g_str_equal,
		g_free, g_free);
	bool keyed = false, any = false;
	for (int i = 0; lines[i]; i++) {
		g_strchomp(lines[i]);
		if (lines[i][0] && !any) {
			any = true;
			keyed = field_key(lines[i], strchr(lines[i], '='));
		}
	}
	int n = 0;
	for (int i = 0; lines[i] && any; i++) {
		char *line = lines[i];
		if (keyed) {
			char *eq = strchr(line, '=');
			if (field_key(line, eq)) {
				g_hash_table_insert(fields, g_strndup(line, eq - line),
					g_strdup(eq + 1));
			}
		} else if (n == 0 && line[0] == '\0') {
			continue; // blank lines before the first
		} else if (n == 0) {
			g_hash_table_insert(fields, g_strdup(strcmp(s->template,
				"block") == 0 ? "block" : "heading"), g_strdup(line));
			n++;
		} else if (n <= 6) {
			g_hash_table_insert(fields, g_strdup_printf("text%d", n++),
				g_strdup(line));
		}
	}
	g_strfreev(lines);
	if (!any) {
		/* Nothing printed: what was there stays */
		g_hash_table_destroy(fields);
		return;
	}
	if (!g_hash_table_contains(fields, "template")) {
		g_hash_table_insert(fields, g_strdup("template"),
			g_strdup(s->template));
	}
	g_hash_table_destroy(s->fields);
	s->fields = fields;
	widget_update(s->w);
}

static void finished(GObject *source, GAsyncResult *result, gpointer data) {
	struct script *s = data;
	GBytes *out = NULL;
	g_subprocess_communicate_finish(G_SUBPROCESS(source), result, &out, NULL,
		NULL);
	if (s->timeout) {
		g_source_remove(s->timeout);
		s->timeout = 0;
	}
	/* A command that failed says nothing about the tile */
	if (out && g_subprocess_get_if_exited(s->running) &&
			g_subprocess_get_exit_status(s->running) == 0) {
		gsize len = 0;
		const char *text = g_bytes_get_data(out, &len);
		char *valid = text ? g_utf8_make_valid(text, MIN(len, MAX_BYTES)) :
			NULL;
		if (valid) {
			parse(s, valid);
		}
		g_free(valid);
	}
	g_clear_pointer(&out, g_bytes_unref);
	g_clear_object(&s->running);
}

static gboolean too_long(gpointer data) {
	struct script *s = data;
	s->timeout = 0;
	if (s->running) {
		g_subprocess_force_exit(s->running);
	}
	return G_SOURCE_REMOVE;
}

/* Called every second while Start shows, and when it comes up */
static void script_tick(struct widget *w) {
	struct script *s = w->data;
	gint64 now = g_get_monotonic_time();
	if (s->running || (s->last && now - s->last <
			(gint64)s->interval * G_USEC_PER_SEC)) {
		return;
	}
	s->last = now;
	const char *argv[] = { "sh", "-c", s->command, NULL };
	s->running = g_subprocess_newv(argv, G_SUBPROCESS_FLAGS_STDOUT_PIPE |
		G_SUBPROCESS_FLAGS_STDERR_SILENCE, NULL);
	if (s->running == NULL) {
		return;
	}
	g_subprocess_communicate_async(s->running, NULL, NULL, finished, s);
	s->timeout = g_timeout_add_seconds(TIMEOUT_S, too_long, s);
}

static bool script_init(struct widget *w, int argc, char **argv) {
	struct script *s = g_new0(struct script, 1);
	s->w = w;
	s->interval = 60;
	const char *file = NULL;
	for (int i = 1; i + 1 < argc; i += 2) {
		if (strcmp(argv[i], "--file") == 0) {
			file = argv[i + 1];
		} else if (strcmp(argv[i], "--command") == 0) {
			s->command = g_strdup(argv[i + 1]);
		} else if (strcmp(argv[i], "--interval") == 0) {
			s->interval = atoi(argv[i + 1]);
		} else if (strcmp(argv[i], "--template") == 0) {
			s->template = g_strdup(argv[i + 1]);
		} else {
			return false;
		}
	}
	if (file) {
		GKeyFile *kf = g_key_file_new();
		if (!g_key_file_load_from_file(kf, file, G_KEY_FILE_NONE, NULL)) {
			fprintf(stderr, "c8-widget: can't read %s\n", file);
			return false;
		}
		g_free(s->command);
		s->command = g_key_file_get_string(kf, "Widget", "Command", NULL);
		if (g_key_file_has_key(kf, "Widget", "Interval", NULL)) {
			s->interval = g_key_file_get_integer(kf, "Widget", "Interval",
				NULL);
		}
		g_free(s->template);
		s->template = g_key_file_get_string(kf, "Widget", "Template", NULL);
		g_key_file_free(kf);
	}
	if (s->command == NULL || s->command[0] == '\0') {
		fprintf(stderr, "c8-widget: script needs a command\n");
		return false;
	}
	if (s->template == NULL) {
		s->template = g_strdup("text");
	}
	s->interval = MAX(s->interval, 1);
	s->fields = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
	w->data = s;
	return true;
}

static void script_content(struct widget *w, struct content *c) {
	struct script *s = w->data;
	GHashTableIter it;
	gpointer key, value;
	g_hash_table_iter_init(&it, s->fields);
	while (g_hash_table_iter_next(&it, &key, &value)) {
		/* Stealth mode: the login, name, PC name and home folder in what
		 * it printed are the persona's; a picture's path must stay real */
		if (strstr(key, "image")) {
			set(c, key, "%s", (const char *)value);
			continue;
		}
		char *shown = c8_stealth_text(value);
		set(c, key, "%s", shown);
		g_free(shown);
	}
}

const struct widget_kind kind_script = {
	.name = "script",
	.summary = "What a command prints, run every so often",
	.options =
		"                --file FILE.widget  Command, Interval and Template from it\n"
		"                --command 'CMD'     run through sh\n"
		"                --interval SECONDS  between runs (60)\n"
		"                --template NAME     text (the default), block, ...\n",
	.tick_ms = 1000,
	.init = script_init,
	.tick = script_tick,
	.content = script_content,
};
