#define _GNU_SOURCE
#include <arpa/inet.h>
#include <ifaddrs.h>
/* net/if.h before linux/wireless.h, which would pull in linux/if.h */
#include <net/if.h>
#include <linux/wireless.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <time.h>
#include <unistd.h>
#include "clock.h"
#include "stealth.h"
#include "widget.h"

#define MAX_CPUS 64

/* Processor: total load, a bar per thread and the clock speed */

struct cpu_times {
	unsigned long long busy, total;
};

struct processor {
	struct cpu_times prev[MAX_CPUS + 1]; // [0] is all cpus
	double load[MAX_CPUS + 1];
	int ncpus;
	double ghz;
};

static void processor_tick(struct widget *w) {
	struct processor *p = w->data;
	char *stat = read_text("/proc/stat");
	if (stat == NULL) {
		return;
	}
	int n = 0;
	for (char *line = stat; line && strncmp(line, "cpu", 3) == 0 && n <= MAX_CPUS; ) {
		unsigned long long v[8] = { 0 };
		char *fields = strchr(line, ' ');
		sscanf(fields, "%llu %llu %llu %llu %llu %llu %llu %llu",
			&v[0], &v[1], &v[2], &v[3], &v[4], &v[5], &v[6], &v[7]);
		unsigned long long idle = v[3] + v[4];
		unsigned long long total = 0;
		for (int i = 0; i < 8; i++) {
			total += v[i];
		}
		struct cpu_times *prev = &p->prev[n];
		unsigned long long dt = total - prev->total;
		unsigned long long db = (total - idle) - prev->busy;
		p->load[n] = dt > 0 && prev->total > 0 ? 100.0 * db / dt : 0;
		prev->busy = total - idle;
		prev->total = total;
		n++;
		line = strchr(line, '\n');
		line = line ? line + 1 : NULL;
	}
	g_free(stat);
	p->ncpus = n - 1;

	/* Mean of the per-thread clocks, in GHz */
	double khz = 0;
	int counted = 0;
	for (int i = 0; i < p->ncpus; i++) {
		char path[96];
		long v;
		snprintf(path, sizeof(path),
			"/sys/devices/system/cpu/cpu%d/cpufreq/scaling_cur_freq", i);
		if (read_long(path, &v)) {
			khz += v;
			counted++;
		}
	}
	p->ghz = counted ? khz / counted / 1e6 : 0;
	widget_update(w);
}

static int by_load(const void *a, const void *b, void *data) {
	const double *load = data;
	double d = load[*(const int *)b] - load[*(const int *)a];
	return d > 0 ? 1 : d < 0 ? -1 : 0;
}

static void processor_content(struct widget *w, struct content *c) {
	struct processor *p = w->data;
	set(c, "template", "block");
	set(c, "label", "Processor");
	set(c, "block", "%.0f%%", p->load[0]);
	set(c, "meter", "%.0f", p->load[0]);
	set(c, "text1", "%.2f GHz", p->ghz);
	set(c, "text2", "%d threads", p->ncpus);
	/* Wide and large: the busiest threads */
	int order[MAX_CPUS];
	for (int i = 0; i < p->ncpus; i++) {
		order[i] = i + 1;
	}
	g_sort_array(order, p->ncpus, sizeof(int), by_load, p->load);
	for (int i = 0; i < 5 && i < p->ncpus; i++) {
		char key[24];
		snprintf(key, sizeof(key), "wide.text%d", i + 2);
		set(c, key, "thread %d\t%.0f%%", order[i] - 1, p->load[order[i]]);
		snprintf(key, sizeof(key), "large.text%d", i + 2);
		set(c, key, "thread %d\t%.0f%%", order[i] - 1, p->load[order[i]]);
	}
}

static bool processor_init(struct widget *w, int argc, char **argv) {
	w->data = g_new0(struct processor, 1);
	return true;
}

const struct widget_kind kind_processor = {
	.name = "processor",
	.summary = "Load, the busiest threads and clock speed",
	.tick_ms = 1000,
	.init = processor_init,
	.tick = processor_tick,
	.content = processor_content,
};

/* Memory */

struct memory {
	double percent;
	char used[48], swap[32];
};

static long meminfo(const char *text, const char *key) {
	const char *p = strstr(text, key);
	return p ? strtol(p + strlen(key), NULL, 10) : 0;
}

static void memory_tick(struct widget *w) {
	struct memory *m = w->data;
	char *text = read_text("/proc/meminfo");
	if (text == NULL) {
		return;
	}
	double total = meminfo(text, "MemTotal:") * 1024.0;
	double avail = meminfo(text, "MemAvailable:") * 1024.0;
	double swap = (meminfo(text, "SwapTotal:") - meminfo(text, "SwapFree:")) * 1024.0;
	g_free(text);
	char a[16], b[16], s[16];
	format_bytes(total - avail, a, sizeof(a));
	format_bytes(total, b, sizeof(b));
	format_bytes(swap, s, sizeof(s));
	struct memory old = *m;
	m->percent = total > 0 ? 100 * (total - avail) / total : 0;
	snprintf(m->used, sizeof(m->used), "%s / %s", a, b);
	snprintf(m->swap, sizeof(m->swap), "swap %s", s);
	if (memcmp(&old, m, sizeof(old)) != 0) {
		widget_update(w);
	}
}

static void memory_content(struct widget *w, struct content *c) {
	struct memory *m = w->data;
	set(c, "template", "block");
	set(c, "label", "Memory");
	set(c, "block", "%.0f%%", m->percent);
	set(c, "meter", "%.0f", m->percent);
	set(c, "text1", "%s", m->used);
	set(c, "text2", "%s", m->swap);
}

static bool memory_init(struct widget *w, int argc, char **argv) {
	w->data = g_new0(struct memory, 1);
	return true;
}

const struct widget_kind kind_memory = {
	.name = "memory",
	.summary = "Memory and swap in use",
	.tick_ms = 2000,
	.init = memory_init,
	.tick = memory_tick,
	.content = memory_content,
};

/* Storage: one filesystem's space and the disks' read/write rates */

struct storage {
	char *path;
	double percent;
	char used[48], io[48];
	unsigned long long read, written; // sectors, all disks
	gint64 at;
};

static void disk_sectors(unsigned long long *read, unsigned long long *written) {
	*read = *written = 0;
	char *text = read_text("/proc/diskstats");
	if (text == NULL) {
		return;
	}
	for (char *line = strtok(text, "\n"); line; line = strtok(NULL, "\n")) {
		char name[64];
		unsigned long long v[7];
		if (sscanf(line, "%*u %*u %63s %llu %llu %llu %llu %llu %llu %llu",
				name, &v[0], &v[1], &v[2], &v[3], &v[4], &v[5], &v[6]) != 8) {
			continue;
		}
		/* Whole disks only, so partitions aren't counted twice */
		char path[128];
		snprintf(path, sizeof(path), "/sys/block/%s/device", name);
		if (access(path, F_OK) == 0) {
			*read += v[2];
			*written += v[6];
		}
	}
	g_free(text);
}

static void storage_tick(struct widget *w) {
	struct storage *s = w->data;
	struct statvfs st;
	struct storage old = *s;
	if (statvfs(s->path, &st) == 0) {
		double used = (double)(st.f_blocks - st.f_bfree) * st.f_frsize;
		double avail = (double)st.f_bavail * st.f_frsize;
		double size = (double)st.f_blocks * st.f_frsize;
		s->percent = used + avail > 0 ? 100 * used / (used + avail) : 0;
		char a[16], b[16];
		format_bytes(used, a, sizeof(a));
		format_bytes(size, b, sizeof(b));
		snprintf(s->used, sizeof(s->used), "%s / %s", a, b);
	}
	unsigned long long r, wr;
	disk_sectors(&r, &wr);
	gint64 now = g_get_monotonic_time();
	if (s->at > 0 && now > s->at) {
		double secs = (now - s->at) / 1e6;
		char a[16], b[16];
		format_bytes((r - s->read) * 512.0 / secs, a, sizeof(a));
		format_bytes((wr - s->written) * 512.0 / secs, b, sizeof(b));
		snprintf(s->io, sizeof(s->io), "r %s  w %s", a, b);
	}
	s->read = r;
	s->written = wr;
	s->at = now;
	if (old.percent != s->percent || strcmp(old.used, s->used) != 0 ||
			strcmp(old.io, s->io) != 0) {
		widget_update(w);
	}
}

static void storage_content(struct widget *w, struct content *c) {
	struct storage *s = w->data;
	set(c, "template", "block");
	if (s->percent >= 90) {
		set(c, "color", COLOR_ALERT);
	} else if (s->percent >= 75) {
		set(c, "color", COLOR_WARN);
	}
	set(c, "label", strcmp(s->path, "/") == 0 ? "Storage" :
		"Storage  ·  %s", c8_stealth_show(s->path));
	set(c, "block", "%.0f%%", s->percent);
	set(c, "meter", "%.0f", s->percent);
	set(c, "text1", "%s", s->used);
	set(c, "text2", "%s", s->io);
}

static bool storage_init(struct widget *w, int argc, char **argv) {
	struct storage *s = g_new0(struct storage, 1);
	s->path = "/";
	for (int i = 1; i + 1 < argc; i += 2) {
		if (strcmp(argv[i], "--path") == 0) {
			s->path = argv[i + 1];
		} else {
			return false;
		}
	}
	w->data = s;
	return true;
}

const struct widget_kind kind_storage = {
	.name = "storage",
	.summary = "Space used on a filesystem, and disk activity",
	.options = "              --path DIR   the filesystem holding DIR (default /)\n",
	.tick_ms = 1000,
	.init = storage_init,
	.tick = storage_tick,
	.content = storage_content,
};

/* Network: the default route's interface */

struct network {
	char iface[IFNAMSIZ];
	char essid[IW_ESSID_MAX_SIZE + 1];
	char addr[INET_ADDRSTRLEN];
	unsigned long long rx, tx;
	gint64 at;
	double down, up; // bytes per second
};

static bool default_iface(char *out) {
	char *text = read_text("/proc/net/route");
	if (text == NULL) {
		return false;
	}
	bool found = false;
	unsigned long best = ~0ul;
	for (char *line = strtok(text, "\n"); line; line = strtok(NULL, "\n")) {
		char name[IFNAMSIZ];
		unsigned long dest, metric;
		if (sscanf(line, "%15s %lx %*x %*x %*d %*d %lu", name, &dest, &metric) == 3 &&
				dest == 0 && metric < best) {
			best = metric;
			strcpy(out, name);
			found = true;
		}
	}
	g_free(text);
	return found;
}

static void iface_counters(const char *iface, unsigned long long *rx,
		unsigned long long *tx) {
	*rx = *tx = 0;
	char *text = read_text("/proc/net/dev");
	if (text == NULL) {
		return;
	}
	size_t len = strlen(iface);
	for (char *line = strtok(text, "\n"); line; line = strtok(NULL, "\n")) {
		while (*line == ' ') {
			line++;
		}
		if (strncmp(line, iface, len) == 0 && line[len] == ':') {
			sscanf(line + len + 1, "%llu %*u %*u %*u %*u %*u %*u %*u %llu", rx, tx);
		}
	}
	g_free(text);
}

static void iface_details(struct network *n) {
	n->essid[0] = n->addr[0] = '\0';
	int fd = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
	if (fd >= 0) {
		struct iwreq req = { 0 };
		snprintf(req.ifr_name, sizeof(req.ifr_name), "%s", n->iface);
		req.u.essid.pointer = n->essid;
		req.u.essid.length = sizeof(n->essid) - 1;
		if (ioctl(fd, SIOCGIWESSID, &req) == 0) {
			n->essid[req.u.essid.length] = '\0';
		} else {
			n->essid[0] = '\0';
		}
		close(fd);
	}
	struct ifaddrs *addrs;
	if (getifaddrs(&addrs) == 0) {
		for (struct ifaddrs *a = addrs; a; a = a->ifa_next) {
			if (a->ifa_addr && a->ifa_addr->sa_family == AF_INET &&
					strcmp(a->ifa_name, n->iface) == 0) {
				inet_ntop(AF_INET, &((struct sockaddr_in *)a->ifa_addr)->sin_addr,
					n->addr, sizeof(n->addr));
				break;
			}
		}
		freeifaddrs(addrs);
	}
}

static void network_tick(struct widget *w) {
	struct network *n = w->data;
	char iface[IFNAMSIZ] = "";
	if (!default_iface(iface)) {
		if (n->iface[0]) {
			n->iface[0] = '\0';
			widget_update(w);
		}
		return;
	}
	if (strcmp(iface, n->iface) != 0) {
		strcpy(n->iface, iface);
		n->at = 0;
	}
	/* Names and addresses change rarely; check every ten seconds */
	static int ticks;
	if (n->at == 0 || ticks++ % 10 == 0) {
		iface_details(n);
	}
	unsigned long long rx, tx;
	iface_counters(n->iface, &rx, &tx);
	gint64 now = g_get_monotonic_time();
	if (n->at > 0 && now > n->at) {
		double secs = (now - n->at) / 1e6;
		n->down = (rx - n->rx) / secs;
		n->up = (tx - n->tx) / secs;
	}
	n->rx = rx;
	n->tx = tx;
	n->at = now;
	widget_update(w);
}

static void network_content(struct widget *w, struct content *c) {
	struct network *n = w->data;
	if (n->iface[0] == '\0') {
		set(c, "template", "block");
		set(c, "block", "offline");
		set(c, "label", "Network");
		return;
	}
	char down[16], up[16];
	format_bytes(n->down, down, sizeof(down));
	format_bytes(n->up, up, sizeof(up));
	/* Stealth mode: a made-up network name and address */
	const char *name = n->essid[0] ? c8_stealth_alias(C8_STEALTH_WIFI,
		n->essid) : n->iface;
	const char *addr = n->addr[0] ? c8_stealth_alias(C8_STEALTH_ADDRESS,
		n->addr) : "";
	set(c, "template", "block");
	set(c, "block", "%s", down);
	set(c, "text1", "down");
	set(c, "text2", "up\t%s", up);
	set(c, "label", "%s", name);
	/* Wide: the details beside the rate */
	set(c, "wide.text3", "interface\t%s", n->iface);
	set(c, "wide.text4", "address\t%s", addr);
	set(c, "large.text3", "interface\t%s", n->iface);
	set(c, "large.text4", "address\t%s", addr);
}

static bool network_init(struct widget *w, int argc, char **argv) {
	w->data = g_new0(struct network, 1);
	return true;
}

const struct widget_kind kind_network = {
	.name = "network",
	.summary = "Download and upload rates on the default connection",
	.tick_ms = 1000,
	.init = network_init,
	.tick = network_tick,
	.content = network_content,
};

/* Battery */

struct battery {
	char dir[128];
	bool present;
	long percent;
	char status[32], time[32];
};

static void battery_find(struct battery *b) {
	b->present = false;
	GDir *dir = g_dir_open("/sys/class/power_supply", 0, NULL);
	if (dir == NULL) {
		return;
	}
	const char *name;
	while ((name = g_dir_read_name(dir)) != NULL) {
		char path[256];
		snprintf(path, sizeof(path), "/sys/class/power_supply/%s/type", name);
		char *type = read_text(path);
		bool battery = type && strncmp(type, "Battery", 7) == 0;
		g_free(type);
		/* Skip peripherals (mice, headsets) that report a battery too */
		snprintf(path, sizeof(path), "/sys/class/power_supply/%s/scope", name);
		char *scope = read_text(path);
		bool device = scope && strncmp(scope, "Device", 6) == 0;
		g_free(scope);
		if (battery && !device) {
			snprintf(b->dir, sizeof(b->dir), "/sys/class/power_supply/%s", name);
			b->present = true;
			break;
		}
	}
	g_dir_close(dir);
}

static void battery_tick(struct widget *w) {
	struct battery *b = w->data;
	struct battery old = *b;
	if (!b->present) {
		battery_find(b);
	}
	char path[192];
	snprintf(path, sizeof(path), "%s/capacity", b->dir);
	if (!b->present || !read_long(path, &b->percent)) {
		b->present = false;
		if (old.present) {
			widget_update(w);
		}
		return;
	}
	snprintf(path, sizeof(path), "%s/status", b->dir);
	char *status = read_text(path);
	snprintf(b->status, sizeof(b->status), "%s", status ? g_strstrip(status) : "");
	g_free(status);
	for (char *p = b->status; *p; p++) {
		*p = g_ascii_tolower(*p);
	}

	/* Time to empty or full, from energy (µWh) or charge (µAh) */
	long now = 0, full = 0, rate = 0;
	snprintf(path, sizeof(path), "%s/energy_now", b->dir);
	bool energy = read_long(path, &now);
	snprintf(path, sizeof(path), "%s/%s", b->dir, energy ? "energy_full" : "charge_full");
	read_long(path, &full);
	if (!energy) {
		snprintf(path, sizeof(path), "%s/charge_now", b->dir);
		read_long(path, &now);
	}
	snprintf(path, sizeof(path), "%s/%s", b->dir, energy ? "power_now" : "current_now");
	read_long(path, &rate);
	b->time[0] = '\0';
	double hours = 0;
	if (rate > 0 && strcmp(b->status, "discharging") == 0) {
		hours = (double)now / rate;
	} else if (rate > 0 && strcmp(b->status, "charging") == 0) {
		hours = (double)(full - now) / rate;
	}
	if (hours > 0 && hours < 48) {
		int mins = (int)(hours * 60);
		snprintf(b->time, sizeof(b->time), "%dh %02dm %s", mins / 60, mins % 60,
			strcmp(b->status, "charging") == 0 ? "to full" : "left");
	}
	if (memcmp(&old, b, sizeof(old)) != 0) {
		widget_update(w);
	}
}

static void battery_content(struct widget *w, struct content *c) {
	struct battery *b = w->data;
	set(c, "label", "Battery");
	if (!b->present) {
		set(c, "heading", "no battery");
		return;
	}
	bool charging = strncmp(b->status, "charg", 5) == 0 ||
		strcmp(b->status, "full") == 0;
	if (!charging && b->percent <= 15) {
		set(c, "color", COLOR_ALERT);
	}
	set(c, "template", "block");
	set(c, "block", "%ld%%", b->percent);
	set(c, "meter", "%ld", b->percent);
	set(c, "text1", "%s", b->status);
	set(c, "text2", "%s", b->time);
}

static bool battery_init(struct widget *w, int argc, char **argv) {
	w->data = g_new0(struct battery, 1);
	return true;
}

const struct widget_kind kind_battery = {
	.name = "battery",
	.summary = "Charge, state and time remaining",
	.tick_ms = 5000,
	.init = battery_init,
	.tick = battery_tick,
	.content = battery_content,
};

/* Sensors: four mini tiles of temperatures, fan and load */

struct sensors {
	double cpu, disk, load;
	long fan;
	bool have_cpu, have_disk, have_fan;
};

/* The first readable `file` of the hwmon device called one of `names` */
static bool hwmon_read(const char *const *names, const char *file, long *out) {
	for (int i = 0; i < 32; i++) {
		char path[128];
		snprintf(path, sizeof(path), "/sys/class/hwmon/hwmon%d/name", i);
		char *name = read_text(path);
		if (name == NULL) {
			continue;
		}
		g_strstrip(name);
		bool match = false;
		for (const char *const *n = names; *n; n++) {
			match |= strcmp(name, *n) == 0;
		}
		g_free(name);
		snprintf(path, sizeof(path), "/sys/class/hwmon/hwmon%d/%s", i, file);
		if (match && read_long(path, out)) {
			return true;
		}
	}
	return false;
}

static void sensors_tick(struct widget *w) {
	struct sensors *s = w->data;
	struct sensors old = *s;
	static const char *const cpu[] = { "coretemp", "k10temp", "zenpower",
		"cpu_thermal", "acpitz", NULL };
	static const char *const disk[] = { "nvme", "drivetemp", NULL };
	long v;
	if ((s->have_cpu = hwmon_read(cpu, "temp1_input", &v))) {
		s->cpu = v / 1000.0;
	}
	if ((s->have_disk = hwmon_read(disk, "temp1_input", &v))) {
		s->disk = v / 1000.0;
	}
	/* Any hwmon device with a fan */
	s->have_fan = false;
	for (int i = 0; i < 32 && !s->have_fan; i++) {
		char path[128];
		snprintf(path, sizeof(path), "/sys/class/hwmon/hwmon%d/fan1_input", i);
		if (read_long(path, &s->fan)) {
			s->have_fan = true;
		}
	}
	char *loadavg = read_text("/proc/loadavg");
	s->load = loadavg ? g_ascii_strtod(loadavg, NULL) : 0;
	g_free(loadavg);
	if (memcmp(&old, s, sizeof(old)) != 0) {
		widget_update(w);
	}
}

static void sensors_content(struct widget *w, struct content *c) {
	struct sensors *s = w->data;
	set(c, "template", "stats");
	set(c, "value1", s->have_cpu ? "%.0f°" : "–", s->cpu);
	set(c, "value2", s->have_disk ? "%.0f°" : "–", s->disk);
	set(c, "value3", s->have_fan ? "%ld" : "–", s->fan);
	set(c, "value4", "%.2f", s->load);
	set(c, "text1", "cpu");
	set(c, "text2", "disk");
	set(c, "text3", "fan rpm");
	set(c, "text4", "load");
	if (s->have_cpu && s->cpu >= 85) {
		set(c, "color1", COLOR_ALERT);
	} else if (s->have_cpu && s->cpu >= 70) {
		set(c, "color1", COLOR_WARN);
	}
}

static bool sensors_init(struct widget *w, int argc, char **argv) {
	w->data = g_new0(struct sensors, 1);
	return true;
}

const struct widget_kind kind_sensors = {
	.name = "sensors",
	.summary = "CPU and disk temperature, fan speed and load",
	.tick_ms = 2000,
	.init = sensors_init,
	.tick = sensors_tick,
	.content = sensors_content,
};

/* Updates: pending packages, from zypper. Listing them costs zypper a few
 * CPU-seconds, so it only runs when the package database or the repository
 * metadata changed, or every few hours. */

#define UPDATES_CHECK_MS (5 * 60 * 1000)
#define UPDATES_MAX_AGE (6 * 3600)
#define MAX_NOTABLE 5

struct updates {
	char **notable_names;
	bool supported, running, checked;
	int count;
	bool kernel;
	char at[16];
	char *notable[MAX_NOTABLE], *versions[MAX_NOTABLE];
	int notable_count;
	gint64 signature, last;
};

static gint64 updates_signature(void) {
	gint64 sig = 0;
	struct stat st;
	if (stat("/usr/lib/sysimage/rpm/Packages.db", &st) == 0) {
		sig = st.st_mtime;
	}
	GDir *dir = g_dir_open("/var/cache/zypp/solv", 0, NULL);
	if (dir) {
		const char *name;
		while ((name = g_dir_read_name(dir)) != NULL) {
			char *path = g_build_filename("/var/cache/zypp/solv", name, "solv", NULL);
			if (stat(path, &st) == 0) {
				sig = sig * 31 + st.st_mtime;
			}
			g_free(path);
		}
		g_dir_close(dir);
	}
	return sig;
}

static void updates_done(struct widget *w, const char *out) {
	struct updates *u = w->data;
	u->running = false;
	if (out == NULL) {
		return; /* e.g. zypper was locked; try again next time */
	}
	for (int i = 0; i < u->notable_count; i++) {
		g_free(u->notable[i]);
		g_free(u->versions[i]);
	}
	u->notable_count = 0;
	u->count = 0;
	u->kernel = false;
	/* Rows look like: v | repo | name | current | available | arch */
	char **lines = g_strsplit(out, "\n", -1);
	for (char **notable = u->notable_names; *notable; notable++) {
		for (char **line = lines; *line; line++) {
			char **cols = g_strsplit(*line, "|", -1);
			if (g_strv_length(cols) >= 5 && strcmp(g_strstrip(cols[0]), "v") == 0 &&
					strcmp(g_strstrip(cols[2]), *notable) == 0 &&
					u->notable_count < MAX_NOTABLE) {
				char *version = g_strstrip(cols[4]);
				version[strcspn(version, "-")] = '\0';
				u->notable[u->notable_count] = g_strdup(*notable);
				u->versions[u->notable_count++] = g_strdup(version);
			}
			g_strfreev(cols);
		}
	}
	for (char **line = lines; *line; line++) {
		char **cols = g_strsplit(*line, "|", -1);
		if (g_strv_length(cols) >= 5 && strcmp(g_strstrip(cols[0]), "v") == 0) {
			u->count++;
			u->kernel |= strcmp(g_strstrip(cols[2]), "kernel-default") == 0;
		}
		g_strfreev(cols);
	}
	g_strfreev(lines);
	time_t now = time(NULL);
	clock_format(u->at, sizeof(u->at), localtime(&now), clock_mode(), true);
	u->checked = true;
	widget_update(w);
}

static void updates_check(struct widget *w) {
	struct updates *u = w->data;
	gint64 sig = updates_signature();
	gint64 now = g_get_real_time() / G_USEC_PER_SEC;
	if (u->running || (u->checked && sig == u->signature &&
			now - u->last < UPDATES_MAX_AGE)) {
		return;
	}
	/* As this user and without refreshing, which needs root; list-updates
	 * --all matches what a dist upgrade would bring in */
	static const char *const argv[] = { "nice", "-n", "19", "zypper", "--quiet",
		"--non-interactive", "--no-refresh", "list-updates", "--all", NULL };
	u->running = run_command(w, argv, updates_done);
	u->signature = sig;
	u->last = now;
}

static gboolean updates_timer(gpointer data) {
	updates_check(data);
	return G_SOURCE_CONTINUE;
}

static void updates_content(struct widget *w, struct content *c) {
	struct updates *u = w->data;
	if (!u->supported) {
		set(c, "heading", "zypper not found");
		set(c, "label", "Updates");
		return;
	}
	if (!u->checked) {
		set(c, "heading", "checking…");
		set(c, "label", "Updates");
		return;
	}
	set(c, "label", "Updates  ·  %s", u->at);
	/* A kernel update wants a restart, so it turns the tile orange */
	if (u->kernel) {
		set(c, "color", COLOR_WARN);
	}
	if (u->count == 0) {
		set(c, "heading", "up to date");
		return;
	}
	set(c, "template", "block");
	set(c, "block", "%d", u->count);
	set(c, "text1", u->count == 1 ? "update available" :
		"updates available");
	/* Notable packages in this batch, then how many others */
	int line = 2;
	for (int i = 0; i < u->notable_count && line <= 5; i++, line++) {
		char key[8];
		snprintf(key, sizeof(key), "text%d", line);
		set(c, key, "%s\t%s", u->notable[i], u->versions[i]);
	}
	if (u->count > line - 2) {
		char key[8];
		snprintf(key, sizeof(key), "text%d", line);
		set(c, key, line > 2 ? "+%d more" : "no notable packages",
			u->count - (line - 2));
	}
}

static bool updates_init(struct widget *w, int argc, char **argv) {
	struct updates *u = g_new0(struct updates, 1);
	const char *notable = "kernel-default,kernel-firmware,glibc,systemd,Mesa,"
		"pipewire,NetworkManager,wlroots,MozillaFirefox,zypper,cont8nuum";
	for (int i = 1; i + 1 < argc; i += 2) {
		if (strcmp(argv[i], "--notable") == 0) {
			notable = argv[i + 1];
		} else {
			return false;
		}
	}
	u->notable_names = g_strsplit(notable, ",", -1);
	u->supported = have_program("zypper");
	w->data = u;
	if (u->supported) {
		updates_check(w);
		g_timeout_add(UPDATES_CHECK_MS, updates_timer, w);
	}
	return true;
}

const struct widget_kind kind_updates = {
	.name = "updates",
	.summary = "Pending package updates (zypper)",
	.options = "              --notable a,b,c   packages to list by name\n",
	.init = updates_init,
	.content = updates_content,
};
