#define _POSIX_C_SOURCE 200809
#include <string.h>
#include <stdio.h>
#include <unistd.h>

#include <X11/Xlib.h>

int main(int argc, char *argv[])
{
	char *bannermsg = "UNCLASSIFIED";
	char *background = "darkgreen";
	char *foreground = "white";
	int c;

	while ((c = getopt(argc, argv, "b:f:")) != -1) {
		switch (c) {
		case 'b':
			background = optarg;
			break;
		case 'f':
			foreground = optarg;
			break;
		default:
			return 1;
		}
	}

	if (optind < argc) {
		bannermsg = argv[optind];
	}

	Display *dpy = XOpenDisplay(NULL);
	Window root = XDefaultRootWindow(dpy);

	XColor bg, fg;
	Colormap cmap = XDefaultColormap(dpy, 0);
	if (XParseColor(dpy, cmap, background, &bg) == 0) {
		fprintf(stderr, "couldn't find color %s\n", background);
		bg.pixel = WhitePixel(dpy, 0);
	} else if (XAllocColor(dpy, DefaultColormap(dpy, 0), &bg) == 0) {
		fprintf(stderr, "couldn't allocate color %s\n", background);
		bg.pixel = WhitePixel(dpy, 0);
	}

	if (XParseColor(dpy, cmap, foreground, &fg) == 0) {
		fprintf(stderr, "couldn't find color %s\n", foreground);
		fg.pixel = BlackPixel(dpy, 0);
	} else if (XAllocColor(dpy, DefaultColormap(dpy, 0), &fg) == 0) {
		fprintf(stderr, "couldn't allocate color %s\n", foreground);
		fg.pixel = BlackPixel(dpy, 0);
	}

	int textheight = 10;
	int width = XDisplayWidth(dpy, 0) / 2;

	/* FIXME: use actual font metrics */
	int textwidth = 6 * strlen(bannermsg);

	Window w = XCreateSimpleWindow(dpy, root, 0, 0, XDisplayWidth(dpy, 0) / 2, textheight + 2, 0, 0, bg.pixel);
	XStoreName(dpy, w, "banner");
	XSelectInput(dpy, w, ExposureMask);
	XMapRaised(dpy, w);

	XSetForeground(dpy, DefaultGC(dpy, 0), fg.pixel);

	for (;;) {
		XEvent ev;
		XNextEvent(dpy, &ev);
		if (ev.type == Expose) {
			XDrawString(dpy, w, DefaultGC(dpy, 0), (width - textwidth) / 2, textheight, bannermsg, strlen(bannermsg));
		}
	}

	return 0;
}