#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include <lirc_client.h>
#include <xosd.h>

#define WAIT_TIME 3
#define SHUTDOWN_COMMAND "sudo halt"

#define PROG_NAME "shutdown_lirc"
#define LIRC_CONFIG_FILE NULL

#define XOSD_FONT "-adobe-helvetica-bold-r-normal--*-240-*-*-*-*-iso8859-1"
#define XOSD_COLOR "red"
#define XOSD_OUTLINE_WIDTH 1
#define XOSD_OUTLINE_COLOR "black"

/* wait until the string s.
   returns 0 if successful, and -1 on failure.  */
int wait_for_string(struct lirc_config *config, const char *s)
{
	char *code;
	char *c;
	int ret;

	while (lirc_nextcode(&code) == 0) {
		if (code == NULL) continue;
		while ((ret = lirc_code2char(config, code, &c)) == 0 &&
		       c != NULL) {
			if (strcmp(c, s) == 0)
				return 0;
		}
		free(code);
		if (ret == -1) break;
	}
	return -1;
}

int main(int argc, char *argv[])
{
	struct lirc_config *config;
	xosd *osd;

	if (lirc_init(PROG_NAME, 1) == -1) 
		exit(1);
	if (lirc_readconfig(LIRC_CONFIG_FILE, &config, NULL) == -1)
		exit(1);

	osd = xosd_create(1);
	if (osd == NULL) {
		perror("osd_create");
		exit(1);
	}
	
	xosd_set_font(osd, XOSD_FONT);
	xosd_set_colour(osd, XOSD_COLOR);
	xosd_set_outline_offset(osd, XOSD_OUTLINE_WIDTH);
	xosd_set_outline_colour(osd, XOSD_OUTLINE_COLOR);
	xosd_set_pos(osd, XOSD_middle);
	xosd_set_align(osd, XOSD_center);

	xosd_display(osd, 0, XOSD_string, "Press 'power' to shut down...");

	alarm(WAIT_TIME);

	if (wait_for_string(config, "shutdown") == 0) {
		xosd_display(osd, 0, XOSD_string, "Shutting down...");
		system(SHUTDOWN_COMMAND);
	}

	xosd_destroy(osd);

	lirc_freeconfig(config);
	lirc_deinit();

	exit(0);
}