insomnia

A frontend for the hii IRC client

git clone https://git.8pit.net/insomnia.git

 1#include <err.h>
 2#include <errno.h>
 3#include <time.h>
 4#include <stdio.h>
 5#include <stdlib.h>
 6#include <time.h>
 7#include <unistd.h>
 8
 9#include <sys/types.h>
10
11static int prevday = -1;
12
13static char *
14xstrftime(char *fmt, struct tm *tm)
15{
16	static char tbuf[256];
17
18	if (!strftime(tbuf, sizeof(tbuf), fmt, tm)) {
19		warnx("strftime failed for '%s'", fmt);
20		return NULL;
21	}
22
23	return tbuf;
24}
25
26static void
27inloop(char *cfmt, char *nfmt)
28{
29	static char *line;
30	static size_t llen;
31	char *tend, *tptr, *tbuf;
32	unsigned long long epoch;
33	struct tm *tm;
34
35	while (getline(&line, &llen, stdin) != -1) {
36		tptr = NULL;
37
38		errno = 0;
39		epoch = strtoull(line, &tend, 10);
40		if (errno || !(tm = localtime((time_t*)&epoch)))
41			goto cont;
42
43		if (*nfmt != '\0') {
44			if (prevday == -1 || prevday != tm->tm_yday) {
45				if ((tbuf = xstrftime(nfmt, tm)))
46					printf("Day changed to %s\n", tbuf);
47			}
48
49			prevday = tm->tm_yday;
50		}
51
52		if (*cfmt != '\0') {
53			if ((tbuf = xstrftime(cfmt, tm)))
54				tptr = tbuf;
55		}
56
57cont:
58		if (tptr)
59			printf("%s%s", tptr, tend);
60		else
61			printf("%s", tend);
62	}
63
64	if (ferror(stdin))
65		errx(EXIT_FAILURE, "ferror failed");
66	free(line);
67}
68
69int
70main(int argc, char **argv)
71{
72	char *cfmt, *nfmt;
73	int opt;
74
75#ifdef __OpenBSD__
76	if (pledge("stdio", NULL) == -1)
77		err(EXIT_FAILURE, "pledge failed");
78#endif
79
80	nfmt = cfmt = NULL;
81	while ((opt = getopt(argc, argv, "n:c:")) != -1) {
82		switch (opt) {
83		case 'n':
84			nfmt = optarg;
85			break;
86		case 'c':
87			cfmt = optarg;
88			break;
89		}
90	}
91
92	if (!cfmt)
93		cfmt = "%X";
94	if (!nfmt)
95		nfmt = "%d %b %Y";
96
97	inloop(cfmt, nfmt);
98	return EXIT_SUCCESS;
99}