#include <stdlib.h>
#include <string.h>
#include <linux/input.h>
#include <linux/uinput.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/time.h>

struct event {
	struct timeval time;
	unsigned short type, code;
	int val;
};

void send_event(int fd, __u16 type, __u16 code, __s32 value) {
	struct input_event ev;
	memset(&ev, 0, sizeof(ev));
	gettimeofday(&ev.time, NULL);
	ev.type = type;
	ev.code = code;
	ev.value = value;
	if (write(fd, &ev, sizeof(ev)) != sizeof(ev)) {
		printf("Error sending event\n");
		exit(-1);
	}
}

int main(int argc, char **argv) {
	int fd = open("/dev/input/uinput", O_WRONLY | O_NDELAY);
	if (fd < 0) {
		printf("bad open\n");
		exit(-1);
	}

	struct uinput_user_dev dev;
	memset(&dev, 0, sizeof(dev));
	strncpy(dev.name, "Microsoft Natural Keyboard", UINPUT_MAX_NAME_SIZE);
	dev.id.version = 4;
	dev.id.bustype = BUS_USB;

	write(fd, &dev, sizeof(dev));

	ioctl(fd, UI_SET_EVBIT, EV_KEY);
	ioctl(fd, UI_SET_EVBIT, EV_REL);
	ioctl(fd, UI_SET_EVBIT, EV_SYN);
	ioctl(fd, UI_SET_RELBIT, REL_WHEEL);

	if (ioctl(fd, UI_DEV_CREATE, NULL)) {
		printf("unable to create uinput device\n");
		exit(-1);
	}

	int ev_fd = open("/dev/input/event6", O_RDONLY);
	if (ev_fd < 0) {
		printf("couldn't open event6\n");
		exit(-1);
	}


	// .code = 419 for push down, 418 for push up
	// .val = 1 for press, 0 for release, 2 for rep

	struct event event;
	for (;;) {
		read(ev_fd, &event, sizeof(struct event));
		if (event.type == 1) {
			if (event.code == 418) { // push scroll up
				send_event(fd, EV_REL, REL_WHEEL, 1);
				send_event(fd, EV_SYN, SYN_REPORT, 0);
			} else if (event.code == 419) { // down
				send_event(fd, EV_REL, REL_WHEEL, -1);
				send_event(fd, EV_SYN, SYN_REPORT, 0);
			}
		}
	}

	ioctl(fd, UI_DEV_DESTROY);

	close(fd);
}
