#define _DEFAULT_SOURCE /* for getopt() and optarg */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/time.h>
#include <pwd.h>
#include <grp.h>
#include <signal.h>
#include <limits.h>

#include <sys/resource.h>
#include <sys/mman.h>

#include <linux/input.h>
#include <linux/uinput.h>

#ifndef VERSION
#define VERSION "(unknown ver)"
#endif

#define DEFAULT_DELAY_MS 30

#ifndef DEFAULT_KBD
#define DEFAULT_KBD "/dev/input/by-id/usb-Marson_Marson_Keyboard_and_Mouse_Link_Ver:ps2120L-event-kbd"
#endif

#define DEFAULT_USER  "nobody"
#define DEFAULT_GROUP "nobody"

/* uinput.h defines KEY_MAX for use with UI_SET_KEYBIT, but the
   mouse buttons are included in the key constants, which makes
   xinput think we're both a keyboard and a pointer. actual
   keyboard keys stop before that. */
#define LAST_KBD_KEY 255

const char *self;

int debugging = 0;                      /* -v */
int foreground = 0;                     /* -v */
const char *keyboard_dev = DEFAULT_KBD; /* -k */
int delay_ms = DEFAULT_DELAY_MS;        /* -d */
int shift_ms = 0;                       /* -s, -d */
int pause_ms = 0;                       /* -p */

int infd = -1, outfd = -1;

void cleanup(void);

/* variadic macros are apparently C99 and not just a GNU extension */
void logmsg(const char *prefix, const char *fmt, ...) {
	va_list ap;
	va_start(ap, fmt);
	fprintf(stderr, "%s: %s: ", self, prefix);
	vfprintf(stderr, fmt, ap);
	va_end(ap);
	fputc('\n', stderr);
}

#define die(fmt,  ...)  { logmsg("fatal",   fmt, ##__VA_ARGS__); cleanup(); exit(1); };
#define warn(fmt, ...)  { logmsg("warning", fmt, ##__VA_ARGS__); };
#define info(fmt, ...)  { logmsg("info",    fmt, ##__VA_ARGS__); };
#define debug(fmt, ...) { if(debugging) logmsg("debug",    fmt, ##__VA_ARGS__); };
#define debug_fg(fmt, ...) { if(debugging && foreground) logmsg("debug",    fmt, ##__VA_ARGS__); };

void set_self(const char *argv0) {
   char *p;
   self = argv0;
   p = strrchr(self, '/');
   if(p) self = p + 1;
}

void print_help(void) {
	/* helptext comes from usage.c, which gets generated by mkusage.pl,
	   from the content in the the .rst file. */
	extern const char *helptext[];

	const char **helpline;

	puts("marsond " VERSION ", by B. Watson <urchlay@slackware.uk>, WTFPL");
	puts("Usage:");

	for(helpline = helptext; *helpline; helpline++)
		puts(*helpline);

	puts(  "Compiled-in defaults:");
	puts(  "  -k: " DEFAULT_KBD);
	printf("  -d: %d\n", DEFAULT_DELAY_MS);
}

void version(void) {
	puts(VERSION);
}

int parse_num(const char *num, char opt, int min) {
	char *end;
	int result;

	result = (int)strtol(num, &end, 10);
	if(*end || (result < min)) {
		die("%c option expects an integer >= %d, not '%s'", opt, min, num);
	}
	return result;
}

void parse_args(int argc, char **argv) {
	int opt;

	opterr = 0;

   if(argc >= 2) {
      if(strcmp(argv[1], "--help") == 0) {
         print_help();
         exit(0);
      } else if(strcmp(argv[1], "--version") == 0) {
         version();
         exit(0);
      }
   }

	while( (opt = getopt(argc, argv, ":d:s:hfk:p:vV")) != -1) {
		switch(opt) {
			case 'd': delay_ms = parse_num(optarg, 'd', 1); break;
			case 's': shift_ms = parse_num(optarg, 's', 1); break;
			case 'f': foreground++;            break;
			case 'h': print_help(); exit(0);   break;
			case 'k': keyboard_dev = optarg;   break;
			case 'p': pause_ms = parse_num(optarg, 'p', 0); break;
			case 'v': debugging++;             break;
			case 'V': version(); exit(0);      break;
			case ':': die("option -%c requires an argument (try --help)", optopt); break;
			default:  die("invalid option -%c (try --help)", optopt); break;
		}
	}

	if(optind < argc) {
		die("unknown argument: %s", argv[optind]);
	}

	if(!shift_ms) shift_ms = delay_ms * 4;
}

/* cleanup() gets called by die() and sighandler() */
void cleanup(void) {
	if(outfd != -1) {
		ioctl(outfd, UI_DEV_DESTROY);
		close(outfd);
		outfd = -1;
	}

	if(infd != -1) {
		ioctl(infd, EVIOCGRAB, 0);
		close(infd);
		infd = -1;
	}
}

/* (try to) exit cleanly if we get a SIGTERM.
   I say "try" because ioctl() (used by cleanup()) is not listed as
   async-signal-safe in signal-safety(7). However, it does seem to
   work OK.
   If we didn't catch SIGTERM, the result would be that the keyboard
   stops working entirely if marsond was started from udev and
   manually killed. Cleanly exiting allows the physical keyboard to
   keep working (with the Enter key timing issue of course).
 */
void sighandler(int sig, siginfo_t *si, void *unused) {
	if(sig != SIGTERM) {
		/* this should never happen! */
		return;
	}

	cleanup();

   exit(0);
}

void setup_sighandler(void) {
	struct sigaction sa;

	sa.sa_flags = SA_SIGINFO;
	sigemptyset(&sa.sa_mask);
	sa.sa_sigaction = sighandler;

	if(sigaction(SIGTERM, &sa, NULL) < 0) {
		warn("can't catch SIGTERM (WTF?)");
	}
}

/* since every keystroke passes through this daemon, we *don't*
   want it to be swapped out. it would suck if you couldn't type
   because you were compiling something huge... note that we have to
   do this after all the forking, see mlockall(2) for details. */
void lock_memory(void) {
	if(mlockall(MCL_CURRENT) >= 0) {
		debug("mlockall() succeeded");
	} else {
		if(foreground)
			warn("can't lock memory: %s", strerror(errno));
	}
}

/* TODO: look into using *actual* realtime scheduling, as
   described in sched(7). */
void set_realtime(void) {
	if(setpriority(PRIO_PROCESS, 0, -20) >= 0) {
		debug("setpriority() succeeded");
	} else {
		if(foreground)
			warn("can't setpriority(): %s", strerror(errno));
	}
}

void drop_privs(void) {
	const char *user, *group;
	struct passwd *pw;
	struct group *gr;
	gid_t gid;

	user = getenv("MARSON_USER");

	if(!user) user = DEFAULT_USER;

	if( !(pw = getpwnam(user)) ) {
		die("no such user '%s'", user);
	}

	if( (group = getenv("MARSON_GROUP")) ) {
		if( !(gr = getgrnam(user)) ) {
			die("no such group '%s'", group);
		}
		gid = gr->gr_gid;
	} else {
		gid = pw->pw_gid;
	}

	debug("about to drop privileges to user/group %d/%d", pw->pw_uid, gid);

	if(setgid(gid) < 0) {
		die("can't change group ID to %d: %s", gid, strerror(errno));
	}

	if(setuid(pw->pw_uid) < 0) {
		die("can't change user ID to %d: %s", pw->pw_uid, strerror(errno));
	}

	debug("now running as user/group %d/%d", getuid(), getgid());
}

void daemonize(void) {
	int pid;

	pid = fork();
	if(pid < 0) {
		die("fork() failed");
	} else if(pid) {
		/* parent */
		exit(0);
	}

	/* we are the child here */
	setsid();

	pid = fork();
	if(pid < 0) {
		die("fork() failed");
	} else if(pid) {
		/* 2nd generation parent */
		info("forked to background, PID %d", pid);
		exit(0);
	}

	/* we are the grandchild here */

	/* nothing left to say, close stdin/out/err and cd to / so at
	   shutdown time, umount won't trip over our cwd. */
	chdir("/");
	close(0);
	close(1);
	close(2);

	/* nowhere for debug messages to go, so turn it off */
	debugging = 0;

	lock_memory();
	set_realtime();
	drop_privs();
}

void set_evbit(int outfd, int event) {
	if(ioctl(outfd, UI_SET_EVBIT, event) >= 0) {
		debug("UI_SET_EVBIT %d OK");
	} else {
		die("UI_SET_EVBIT %d failed: %s", event, strerror(errno));
	}
}

void get_device_node(char *result) {
	char path[PATH_MAX];

	/* trick here: outfd is the last file we opened. while running, we
	   have an open file descriptor for the virtual device, which *must*
	   be the next integer file descriptor after outfd. */
	snprintf(path, PATH_MAX - 1, "/proc/%d/fd/%d", getpid(), outfd + 1);

	if(readlink(path, result, UINPUT_MAX_NAME_SIZE - 1) < 0)
		strcpy(result, "(unknown)");
}

void print_device_name(void) {
	char name[UINPUT_MAX_NAME_SIZE];

	if(ioctl(outfd, UI_GET_SYSNAME(UINPUT_MAX_NAME_SIZE), name) >= 0) {
		debug("created virtual keyboard device: /sys/devices/virtual/input/%s/", name);
	} else {
		debug("created virtual keyboard device but couldn't get its name (old kernel?)");
	}

	get_device_node(name);
	debug("virtual keyboard device node: %s", name);
}

void write_event(struct input_event *ev) {
	if(write(outfd, ev, sizeof(*ev)) < 0) {
		if(foreground) {
			die("write to /dev/uinput failed: %s", strerror(errno));
		} else {
			exit(1);
		}
	}
}

long long gettime_millis(void) {
	struct timeval tv;

	gettimeofday(&tv, 0);
	return(tv.tv_sec * 1000 + tv.tv_usec / 1000);
}

void release_key(int code) {
	struct input_event ev;

	ev.type = EV_KEY;
	ev.code = code;
	ev.value = 0;

	write_event(&ev);
}

const char *event_type(int type) {
	switch(type) {
		case EV_SYN: return "EV_SYN";
		case EV_MSC: return "EV_MSC";
		case EV_KEY: return "EV_KEY";
		default: return "???";
	}
}

void shift_timing(long long *last, const char *name, int code) {
	if(*last && (gettime_millis() < (*last + shift_ms))) {
		debug_fg("!!! Enter pressed; last %s shift press < %dms ago, sending %s shift release", name, shift_ms, name);
		release_key(code);
		*last = 0;
	}
}

int main(int argc, char **argv) {
	int i;
	long long last_l_shift = 0, last_r_shift = 0;
	struct uinput_user_dev dev;
	struct input_event ev;

	set_self(argv[0]);

	parse_args(argc, argv);

	debug("marsond v" VERSION " starting up");

	if(pause_ms > 0) {
		debug("pausing %dms due to -p option");
		usleep(pause_ms * 1000);
	}

	if((outfd = open("/dev/uinput", O_WRONLY | O_NONBLOCK)) >= 0) {
		debug("opened /dev/uinput");
	} else {
		die("failed to open /dev/uinput: %s", strerror(errno));
	}

	if((infd = open(keyboard_dev, O_RDONLY)) >= 0) {
		debug("opened %s", keyboard_dev);
	} else {
		die("failed to open %s: %s", keyboard_dev, strerror(errno));
	}

	if(ioctl(infd, EVIOCGRAB, 1) >= 0) {
		debug("grabbed %s", keyboard_dev);
	} else {
		if(errno == EBUSY)
			warn("is an instance of %s already running?", self);
		die("failed to grab %s: %s", keyboard_dev, strerror(errno));
	}

	set_evbit(outfd, EV_KEY); /* get and send keystroke events... */
	set_evbit(outfd, EV_SYN); /* ...sync events... */
	set_evbit(outfd, EV_MSC); /* ...and miscellaneous. */
	/* the other event types will never be sent by a keyboard. */

	/* we want all possible keystrokes */
	for(i = 0; i <= LAST_KBD_KEY; i++) {
		if(ioctl(outfd, UI_SET_KEYBIT, i) >= 0) {
			/* we don't wanna be *that* verbose */
		} else {
			die("UI_SET_KEYBIT %d failed: %s", i, strerror(errno));
		}
	}
	debug("UI_SET_KEYBIT OK");

	/* this is the old API. uinput.rst in the kernel sources shows
	   how to use the new API, then recommends using the old API
	   as a fallback for older kernels... I don't see a need to
	   even try the new API, if the old one works. */
	memset(&dev, 0, sizeof(dev));
	snprintf(dev.name, UINPUT_MAX_NAME_SIZE, "marsond virtual keyboard");
	dev.id.bustype = BUS_VIRTUAL;
	dev.id.vendor =  0x69;
	dev.id.product = 0x666;
	dev.id.version = 1;

	if(write(outfd, &dev, sizeof(dev)) >= 0) {
		debug("wrote dev structure to /dev/uinput");
	} else {
		die("write to /dev/uinput failed: %s", strerror(errno));
	}

	/* I was hoping the return value of this ioctl would be the
	   device number, but it's just 0 for no error. */
	if(ioctl(outfd, UI_DEV_CREATE) >= 0) {
		if(debugging) print_device_name();
	} else {
		die("UI_DEV_CREATE failed: %s", strerror(errno));
	}

	setup_sighandler();

	/* this must be done while still running as root... */
	if(foreground) {
		lock_memory();
		set_realtime();
		drop_privs();
		debug("entering event loop");
	} else {
		daemonize();
	}

	/* note: don't call debug() or die() unless foreground is true, since
	   daemonize() closes our stderr (there's nowhere for the messages
	   to print). */
	while(1) {
		if(read(infd, &ev, sizeof(ev)) < 0) {
			if(foreground) {
				die("read from %s failed: %s", keyboard_dev, strerror(errno));
			} else {
				exit(1);
			}
		}

		debug_fg("got event: type %d (%s), code 0x%02x, value %d",
		         ev.type, event_type(ev.type), ev.code, ev.value);

		/* ev.value: 0 == release, 1 == initial press, 2 == repeat */
		if(ev.type == EV_KEY) {
			if(ev.value == 1) {
				if(ev.code == KEY_RIGHTSHIFT) {
					last_r_shift = (ev.value ? gettime_millis() : 0);
					debug_fg("last_r_shift %lld", last_r_shift);
				} else if(ev.code == KEY_LEFTSHIFT) {
					last_l_shift = (ev.value ? gettime_millis() : 0);
					debug_fg("last_l_shift %lld", last_l_shift);
				} else if(ev.code == KEY_ENTER) {
					shift_timing(&last_r_shift, "right", KEY_RIGHTSHIFT);
					shift_timing(&last_l_shift, "left",  KEY_LEFTSHIFT);
				}
			} else if(ev.code == KEY_ENTER && ev.value == 0) {
				debug_fg("!!! got Enter key release, delaying %dms", delay_ms);
				usleep(delay_ms * 1000);
			}
		}

		write_event(&ev);
	}

	exit(1);
}

/*
for the A key:

event: type 4, code 4, value 458756
event: type 1, code 30, value 1
event: type 0, code 0, value 0
event: type 4, code 4, value 458756
event: type 1, code 30, value 0
event: type 0, code 0, value 0

for Enter:

event: type 4, code 4, value 458792
event: type 1, code 28, value 1
event: type 0, code 0, value 0
event: type 4, code 4, value 458792
event: type 1, code 28, value 0
event: type 0, code 0, value 0

Onlt the type 1 messages concern us, but we have to pass
them all through. code 28 is KEY_ENTER, value is 1 for press,
0 for release.

from uinput.h:
type 4 EV_MSC, code 4 MSC_SCAN.
type 0 EV_SYN, code 0 SYN_REPORT.
*/
