/*
 * Copyright (c) 2010, Gražvydas Ignotas
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the organization nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <linux/kd.h>

#define PFX "op_runfbapp: "

static struct termios g_kbd_termios_saved;
static int g_kbdfd;

static Cursor transparent_cursor(Display *display, Window win)
{
	Cursor cursor;
	Pixmap pix;
	XColor dummy;
	char d = 0;

	memset(&dummy, 0, sizeof(dummy));
	pix = XCreateBitmapFromData(display, win, &d, 1, 1);
	cursor = XCreatePixmapCursor(display, pix, pix,
			&dummy, &dummy, 0, 0);
	XFreePixmap(display, pix);
	return cursor;
}

static void *x11_handler(void *arg)
{
	unsigned int display_width, display_height;
	XSetWindowAttributes attributes;
	Window win;
	XEvent report;
	Display *display;
	int screen;

	display = XOpenDisplay(NULL);
	if (display == NULL)
	{
		fprintf(stderr, PFX "(not hiding X): Can't open display: %s\n",
			XDisplayName(NULL));
		return NULL;
	}

	screen = DefaultScreen(display);

	display_width = DisplayWidth(display, screen);
	display_height = DisplayHeight(display, screen);

	win = XCreateSimpleWindow(display,
			RootWindow(display, screen),
			0, 0, display_width, display_height, 0,
			BlackPixel(display, screen),
			BlackPixel(display, screen));

	attributes.override_redirect = True;
	attributes.cursor = transparent_cursor(display, win);
	XChangeWindowAttributes(display, win, CWOverrideRedirect | CWCursor, &attributes);

	XSelectInput(display, win, ExposureMask);
	XMapWindow(display, win);
	XGrabKeyboard(display, win, False, GrabModeAsync, GrabModeAsync, CurrentTime);

	while (1)
	{
		XNextEvent(display, &report);

		if (report.type == Expose)
			while (XCheckTypedEvent(display, Expose, &report))
				;
	}

	return NULL;
}

static void hidecon_start(void)
{
	struct termios kbd_termios;
	int mode;

	g_kbdfd = open("/dev/tty", O_RDWR);
	if (g_kbdfd == -1) {
		perror(PFX "open /dev/tty");
		return;
	}

	if (ioctl(g_kbdfd, KDGETMODE, &mode) == -1) {
		perror(PFX "(not hiding FB): KDGETMODE");
		goto fail;
	}

	if (tcgetattr(g_kbdfd, &kbd_termios) == -1) {
		perror(PFX "tcgetattr");
		goto fail;
	}

	g_kbd_termios_saved = kbd_termios;
	kbd_termios.c_lflag &= ~(ICANON | ECHO); // | ISIG);
	kbd_termios.c_iflag &= ~(ISTRIP | IGNCR | ICRNL | INLCR | IXOFF | IXON);
	kbd_termios.c_cc[VMIN] = 0;
	kbd_termios.c_cc[VTIME] = 0;

	if (tcsetattr(g_kbdfd, TCSAFLUSH, &kbd_termios) == -1) {
		perror(PFX "tcsetattr");
		goto fail;
	}

	if (ioctl(g_kbdfd, KDSETMODE, KD_GRAPHICS) == -1) {
		perror(PFX "KDSETMODE KD_GRAPHICS");
		tcsetattr(g_kbdfd, TCSAFLUSH, &g_kbd_termios_saved);
		goto fail;
	}

	return;

fail:
	close(g_kbdfd);
	g_kbdfd = -1;
}

static void hidecon_end(void)
{
	if (g_kbdfd < 0)
		return;

	if (ioctl(g_kbdfd, KDSETMODE, KD_TEXT) == -1)
		perror(PFX "KDSETMODE KD_TEXT");

	if (tcsetattr(g_kbdfd, TCSAFLUSH, &g_kbd_termios_saved) == -1)
		perror(PFX "tcsetattr");

	close(g_kbdfd);
	g_kbdfd = -1;
}

static void do_exec(char * const argv[])
{
	int ret, status;
	pid_t pid;

	pid = fork();
	if (pid == -1) {
		perror(PFX "fork");
		return;
	}

	if (pid == 0) {
		/* child */
		execvp(argv[0], argv);
		perror(PFX "execvp");
		exit(1);
	}

	ret = waitpid(pid, &status, 0);
	if (ret < 0)
		perror(PFX "waitpid");
}

int main(int argc, char *argv[])
{
	pthread_t tid;
	int ret;

	ret = pthread_create(&tid, NULL, x11_handler, NULL);
	if (ret != 0) {
		fprintf(stderr, PFX "pthread_create: %d\n", ret);
		return 1;
	}
	pthread_detach(tid);

	hidecon_start();

	do_exec(argv + 1);

	hidecon_end();

	/* XXX: maybe stop the X thread nicely? */

	return 0;
}

