/*
 * PC info: what this machine is, read from /proc, /sys and os-release
 * when the page opens. Copy puts it all on the clipboard, for a bug
 * report or a forum post.
 */
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/statvfs.h>
#include <sys/utsname.h>
#include <glib.h>
#include "settings.h"

#define ROWS_MAX 16

static struct {
	char *name[ROWS_MAX], *value[ROWS_MAX];
	int count;
} info;

static void row(const char *name, char *value) {
	if (value == NULL || value[0] == '\0' || info.count == ROWS_MAX) {
		g_free(value);
		return;
	}
	info.name[info.count] = g_strdup(name);
	info.value[info.count++] = value;
}

/* A one-line file, trimmed; NULL when it can't be read */
static char *read_line(const char *path) {
	char *text = NULL;
	if (!g_file_get_contents(path, &text, NULL, NULL)) {
		return NULL;
	}
	return g_strstrip(text);
}

/* Boards built from parts say nothing of use here */
static bool placeholder(const char *s) {
	static const char *const empty[] = { "To Be Filled By O.E.M.",
		"System Product Name", "System manufacturer", "Default string",
		"Not Specified", "Not Applicable" };
	if (s == NULL || s[0] == '\0') {
		return true;
	}
	for (size_t i = 0; i < G_N_ELEMENTS(empty); i++) {
		if (g_ascii_strcasecmp(s, empty[i]) == 0) {
			return true;
		}
	}
	return false;
}

static char *model(void) {
	char *vendor = read_line("/sys/class/dmi/id/sys_vendor");
	char *product = read_line("/sys/class/dmi/id/product_name");
	char *out = NULL;
	if (vendor && g_ascii_strcasecmp(vendor, "LENOVO") == 0) {
		/* Lenovo's product is a part number; the name is the version */
		char *version = read_line("/sys/class/dmi/id/product_version");
		if (!placeholder(version) && !placeholder(product)) {
			out = g_strdup_printf("Lenovo %s (%s)", version, product);
		}
		g_free(version);
	}
	if (out == NULL && !placeholder(product)) {
		/* The maker too, unless the product says it already */
		if (placeholder(vendor) || g_str_has_prefix(product, vendor)) {
			out = g_strdup(product);
		} else {
			out = g_strdup_printf("%s %s", vendor, product);
		}
	}
	g_free(vendor);
	g_free(product);
	return out;
}

static char *processor(void) {
	char *text = NULL;
	if (!g_file_get_contents("/proc/cpuinfo", &text, NULL, NULL)) {
		return NULL;
	}
	char *name = NULL;
	int threads = 0;
	char **lines = g_strsplit(text, "\n", -1);
	for (int i = 0; lines[i]; i++) {
		if (g_str_has_prefix(lines[i], "processor")) {
			threads++;
		}
		/* x86 says "model name"; some ARM boards "Model" or "Hardware" */
		if (name == NULL && (g_str_has_prefix(lines[i], "model name") ||
				g_str_has_prefix(lines[i], "Hardware"))) {
			const char *colon = strchr(lines[i], ':');
			if (colon) {
				name = g_strstrip(g_strdup(colon + 1));
			}
		}
	}
	g_strfreev(lines);
	g_free(text);
	if (name == NULL) {
		struct utsname u;
		uname(&u);
		name = g_strdup(u.machine);
	}
	/* "Intel(R) Core(TM) i5-10210U CPU @ 1.60GHz": the marks say nothing */
	static const char *const marks[] = { "(R)", "(TM)", "(tm)", " CPU" };
	for (size_t i = 0; i < G_N_ELEMENTS(marks); i++) {
		char **parts = g_strsplit(name, marks[i], -1);
		g_free(name);
		name = g_strjoinv("", parts);
		g_strfreev(parts);
	}
	char *out = threads > 1 ?
		g_strdup_printf("%s (%d threads)", name, threads) : g_strdup(name);
	g_free(name);
	return out;
}

/* As drives and memory are sold: 16 GB, 512 GB, 2.0 TB */
static char *size_text(double bytes, bool binary) {
	double unit = binary ? 1024 : 1000;
	double gb = bytes / (unit * unit * unit);
	if (gb >= 1000) {
		return g_strdup_printf("%.1f TB", gb / unit);
	}
	return g_strdup_printf(gb >= 10 ? "%.0f GB" : "%.1f GB", gb);
}

static char *memory(void) {
	char *text = NULL;
	if (!g_file_get_contents("/proc/meminfo", &text, NULL, NULL)) {
		return NULL;
	}
	unsigned long long kb = 0;
	const char *at = strstr(text, "MemTotal:");
	if (at) {
		sscanf(at, "MemTotal: %llu", &kb);
	}
	g_free(text);
	return kb ? size_text(kb * 1024.0, true) : NULL;
}

/* A PCI device's name from hwdata's list, "Vendor Device"; NULL without
 * the list or the device in it */
static char *pci_name(unsigned vendor, unsigned device) {
	static const char *const lists[] = { "/usr/share/hwdata/pci.ids",
		"/usr/share/pci.ids", "/usr/share/misc/pci.ids" };
	FILE *f = NULL;
	for (size_t i = 0; i < G_N_ELEMENTS(lists) && f == NULL; i++) {
		f = fopen(lists[i], "r");
	}
	if (f == NULL) {
		return NULL;
	}
	char line[512], want_v[8], want_d[8];
	snprintf(want_v, sizeof(want_v), "%04x", vendor);
	snprintf(want_d, sizeof(want_d), "%04x", device);
	char *vendor_name = NULL, *out = NULL;
	while (fgets(line, sizeof(line), f)) {
		if (line[0] == '#' || line[0] == '\n') {
			continue;
		}
		if (vendor_name == NULL) {
			if (strncmp(line, want_v, 4) == 0 && line[4] == ' ') {
				vendor_name = g_strstrip(g_strdup(line + 4));
			}
		} else if (line[0] != '\t') {
			break; // the next vendor: ours doesn't list the device
		} else if (line[1] != '\t' && strncmp(line + 1, want_d, 4) == 0) {
			char *dev = g_strstrip(g_strdup(line + 5));
			out = g_strdup_printf("%s %s", vendor_name, dev);
			g_free(dev);
			break;
		}
	}
	fclose(f);
	g_free(vendor_name);
	return out;
}

/* Every graphics card the kernel drives, one a line */
static char *graphics(void) {
	GDir *dir = g_dir_open("/sys/class/drm", 0, NULL);
	if (dir == NULL) {
		return NULL;
	}
	GString *out = g_string_new(NULL);
	const char *name;
	while ((name = g_dir_read_name(dir))) {
		/* card0, not card0-eDP-1 (its outputs) or renderD128 */
		if (!g_str_has_prefix(name, "card") || strchr(name, '-')) {
			continue;
		}
		char *base = g_build_filename("/sys/class/drm", name, "device", NULL);
		char *vpath = g_build_filename(base, "vendor", NULL);
		char *dpath = g_build_filename(base, "device", NULL);
		char *v = read_line(vpath), *d = read_line(dpath);
		char *card = v && d ? pci_name((unsigned)strtoul(v, NULL, 16),
			(unsigned)strtoul(d, NULL, 16)) : NULL;
		if (card == NULL) {
			/* Not PCI, or not in the list: the driver's name at least */
			char *link = g_build_filename(base, "driver", NULL);
			char *target = g_file_read_link(link, NULL);
			card = target ? g_path_get_basename(target) : NULL;
			g_free(target);
			g_free(link);
		}
		if (card && strstr(out->str, card) == NULL) {
			g_string_append_printf(out, "%s%s", out->len ? "\n" : "", card);
		}
		g_free(card);
		g_free(v);
		g_free(d);
		g_free(vpath);
		g_free(dpath);
		g_free(base);
	}
	g_dir_close(dir);
	return g_string_free(out, FALSE);
}

static char *storage(void) {
	struct statvfs fs;
	if (statvfs(g_get_home_dir(), &fs) != 0 || fs.f_blocks == 0) {
		return NULL;
	}
	char *total = size_text((double)fs.f_blocks * fs.f_frsize, false);
	char *left = size_text((double)fs.f_bavail * fs.f_frsize, false);
	char *out = g_strdup_printf("%s, %s free", total, left);
	g_free(total);
	g_free(left);
	return out;
}

static void gather(void) {
	for (int i = 0; i < info.count; i++) {
		g_free(info.name[i]);
		g_free(info.value[i]);
	}
	info.count = 0;
	struct utsname u;
	uname(&u);
	row("PC name", g_strdup(c8_stealth_alias(C8_STEALTH_DEVICE,
		g_get_host_name())));
	row("Model", model());
	row("Processor", processor());
	row("Memory", memory());
	row("Graphics", graphics());
	row("Storage", storage());
	row("System", g_get_os_info(G_OS_INFO_KEY_PRETTY_NAME));
	row("Kernel", g_strdup_printf("%s %s (%s)", u.sysname, u.release,
		u.machine));
	row("Desktop", g_strdup("cont8nuum " C8_VERSION));
}

static void copy_clicked(struct c8ui_widget *w, void *data) {
	GString *text = g_string_new(NULL);
	for (int i = 0; i < info.count; i++) {
		/* Several cards: one a line, each under the same name */
		char **lines = g_strsplit(info.value[i], "\n", -1);
		for (int l = 0; lines[l]; l++) {
			g_string_append_printf(text, "%s: %s\n", info.name[i], lines[l]);
		}
		g_strfreev(lines);
	}
	c8ui_root_set_clipboard(w->root, text->str);
	g_string_free(text, TRUE);
	c8ui_button_set_label(w, "Copied");
}

static struct c8ui_widget *value_label(const char *text) {
	struct c8ui_widget *l = c8ui_label_new(text, C8UI_TEXT_BODY);
	c8ui_label_set_max_lines(l, 6);
	return l;
}

static void info_build(struct c8ui_widget *box) {
	gather();
	/* Each name beside its value; narrow, over it */
	struct c8ui_widget *rows = c8ui_box_new(C8UI_VERTICAL, 14);
	rows->fill = true;
	for (int i = 0; i < info.count; i++) {
		struct c8ui_widget *pair = c8ui_box_new(C8UI_HORIZONTAL, 32);
		c8ui_box_set_narrow_orientation(pair, C8UI_VERTICAL);
		c8ui_box_set_narrow_spacing(pair, 2);
		pair->fill = true;
		struct c8ui_widget *name = caption(info.name[i]);
		name->fixed_width = 110;
		add(pair, name);
		struct c8ui_widget *value = value_label(info.value[i]);
		value->expand = true;
		add(pair, value);
		add(rows, pair);
	}
	add(box, rows);
	add(box, c8ui_button_new("Copy", copy_clicked, NULL));
}

const struct page page_info = {
	.name = "info",
	.title = "PC info",
	.build = info_build,
};
