#define _POSIX_C_SOURCE 200809L
#include <dirent.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

static volatile sig_atomic_t stop;

static void
done(int sig)
{
	(void)sig;
	stop = 1;
}

int
main(int argc, char **argv)
{
	DIR *d;
	struct dirent *de;
	FILE *f;
	char path[128], line[256], name[16], cohort[8192];
	unsigned int uid, ids[3];
	size_t rss, sum, peak = 0, qpdf_peak = 0, used;
	int detail = getenv("SIGNET_RSS_DETAIL") != NULL;
	struct timespec nap = { 0, 1000000 };
	int i, ready = 0, once, track_qpdf, have_qpdf;

	if (argc != 4 && argc != 5)
		return 2;
	once = argc == 5 && strcmp(argv[4], "--once") == 0;
	track_qpdf = argc == 5 && strcmp(argv[4], "--qpdf") == 0;
	if (argc == 5 && !once && !track_qpdf)
		return 2;
	for (i = 0; i < 3; i++)
		ids[i] = (unsigned int)strtoul(argv[i + 1], NULL, 10);
	signal(SIGTERM, done);
	signal(SIGINT, done);
	while (!stop) {
		sum = 0;
		used = 0;
		cohort[0] = '\0';
		have_qpdf = 0;
		if ((d = opendir("/proc")) == NULL)
			return 1;
		while ((de = readdir(d)) != NULL) {
			if (de->d_name[0] < '0' || de->d_name[0] > '9')
				continue;
			if (snprintf(path, sizeof(path), "/proc/%s/status", de->d_name) >= (int)sizeof(path))
				continue;
			if ((f = fopen(path, "r")) == NULL)
				continue;
			uid = (unsigned int)-1;
			rss = 0;
			name[0] = '\0';
			while (fgets(line, sizeof(line), f)) {
				if ((track_qpdf || detail) && sscanf(line, "Name: %15s", name) == 1)
					continue;
				if (sscanf(line, "Uid: %u", &uid) == 1)
					continue;
				if (sscanf(line, "VmRSS: %zu", &rss) == 1)
					continue;
			}
			fclose(f);
			if (uid == ids[0] || uid == ids[1] || uid == ids[2]) {
				sum += rss;
				if (detail && used < sizeof(cohort)) {
					int n = snprintf(cohort + used, sizeof(cohort) - used,
					    " %s:%s:%zu", de->d_name, name, rss);
					if (n > 0)
						used += (size_t)n;
				}
				if (track_qpdf && rss && strcmp(name, "qpdf") == 0)
					have_qpdf = 1;
			}
		}
		closedir(d);
		if (sum > peak)
			peak = sum;
		if (have_qpdf && sum > qpdf_peak) {
			qpdf_peak = sum;
			if (detail)
				fprintf(stderr, "qpdf_cohort_peak=%zu;%s\n", sum, cohort);
		}
		if (!once && !ready) {
			printf("sampler_ready=1\n");
			fflush(stdout);
			ready = 1;
		}
		if (once)
			break;
		nanosleep(&nap, NULL);
	}
	printf("transient_sampled_app_peak_kib=%zu\n", peak);
	if (track_qpdf)
		printf("transient_sampled_qpdf_app_peak_kib=%zu\n", qpdf_peak);
	return 0;
}
