#define _GNU_SOURCE
#include <dirent.h>
#include <fcntl.h>
#include <pthread.h>
#include <sched.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/wait.h>
#include <linux/usb/ch9.h>
#include <linux/usb/raw_gadget.h>

#define MAX_TRANSFER				1024

#define ES2_REQUEST_ARPC_RUN			0x12

#define GB_TYPE_RESPONSE			0x80
#define GB_REQUEST_TYPE_CPORT_SHUTDOWN		0x00
#define GB_SVC_CPORT				0
#define GB_SVC_TYPE_PROTOCOL_VERSION		0x01
#define GB_SVC_TYPE_SVC_HELLO			0x02
#define GB_SVC_TYPE_DME_PEER_GET		0x09
#define GB_SVC_TYPE_DME_PEER_SET		0x0a
#define GB_SVC_TYPE_MODULE_INSERTED		0x1f
#define GB_SVC_TYPE_INTF_VSYS_ENABLE		0x21
#define GB_SVC_TYPE_INTF_REFCLK_ENABLE		0x23
#define GB_SVC_TYPE_INTF_UNIPRO_ENABLE		0x25
#define GB_SVC_TYPE_INTF_ACTIVATE		0x27
#define GB_SVC_INTF_TYPE_GREYBUS		0x03
#define GB_CONTROL_TYPE_VERSION			0x01
#define GB_CONTROL_TYPE_GET_MANIFEST_SIZE	0x03
#define GB_CONTROL_TYPE_GET_MANIFEST		0x04
#define GB_CONTROL_TYPE_BUNDLE_ACTIVATE		0x12

struct greybus_message_header {
	uint16_t size;
	uint16_t operation_id;
	uint8_t type;
	uint8_t result;
	uint8_t host_cport;
	uint8_t pad;
} __attribute__((packed));

static int raw_gadget_fd;
static int arpc_in_endpoint, cport_out_endpoint;
static volatile int cport_in_endpoint = -1;

static const struct usb_device_descriptor es2_device_descriptor = {
	.bLength = USB_DT_DEVICE_SIZE,
	.bDescriptorType = USB_DT_DEVICE,
	.bcdUSB = 0x0200,
	.bMaxPacketSize0 = 64,
	.idVendor = 0x18d1,
	.idProduct = 0x1eaf,
	.bNumConfigurations = 1,
};

static const struct usb_endpoint_descriptor es2_endpoints[3] = {
	{ USB_DT_ENDPOINT_SIZE, USB_DT_ENDPOINT, 0x81, USB_ENDPOINT_XFER_BULK, 512 },
	{ USB_DT_ENDPOINT_SIZE, USB_DT_ENDPOINT, 0x82, USB_ENDPOINT_XFER_BULK, 512 },
	{ USB_DT_ENDPOINT_SIZE, USB_DT_ENDPOINT, 0x01, USB_ENDPOINT_XFER_BULK, 512 },
};

static const unsigned char module_manifest[28] = {
	28, 0, 0, 1,
	8, 0, 1, 0,	0, 0, 0, 0,
	8, 0, 3, 0,	1, 0x0a, 0, 0,
	8, 0, 4, 0,	1, 0, 1, 0x06,
};

static int raw_gadget_io(unsigned long request, int endpoint, void *data, int length)
{
	struct {
		struct usb_raw_ep_io io;
		unsigned char data[MAX_TRANSFER];
	} buffer;
	int is_read = request == USB_RAW_IOCTL_EP_READ || request == USB_RAW_IOCTL_EP0_READ;
	int transferred;

	buffer.io.ep = endpoint;
	buffer.io.flags = 0;
	buffer.io.length = length;
	if (!is_read)
		memcpy(buffer.data, data, length);
	transferred = ioctl(raw_gadget_fd, request, &buffer);
	if (is_read && transferred > 0)
		memcpy(data, buffer.data, transferred);
	return transferred;
}

static void handle_control_request(struct usb_ctrlrequest *ctrl)
{
	unsigned char data[MAX_TRANSFER];
	int reply_length = -1, i;

	if (ctrl->bRequestType & USB_TYPE_VENDOR) {
		if (ctrl->bRequestType & USB_DIR_IN) {
			data[0] = 3;
			data[1] = 0;
			raw_gadget_io(USB_RAW_IOCTL_EP0_WRITE, 0, data, 2);
			return;
		}
		raw_gadget_io(USB_RAW_IOCTL_EP0_READ, 0, data, ctrl->wLength);
		if (ctrl->bRequest == ES2_REQUEST_ARPC_RUN) {
			data[2] = 0;
			raw_gadget_io(USB_RAW_IOCTL_EP_WRITE, arpc_in_endpoint, data, 3);
		}
		return;
	}
	if (ctrl->bRequest == USB_REQ_GET_DESCRIPTOR && (ctrl->wValue >> 8) == USB_DT_DEVICE) {
		reply_length = sizeof(es2_device_descriptor);
		memcpy(data, &es2_device_descriptor, reply_length);
	} else if (ctrl->bRequest == USB_REQ_GET_DESCRIPTOR && (ctrl->wValue >> 8) == USB_DT_CONFIG) {
		static const unsigned char config_and_interface[18] = {
			9, USB_DT_CONFIG, 9 + 9 + 3 * USB_DT_ENDPOINT_SIZE, 0, 1, 1, 0, 0x80, 0xfa,
			9, USB_DT_INTERFACE, 0, 0, 3, 0xff, 0, 0, 0,
		};
		memcpy(data, config_and_interface, 18);
		for (i = 0; i < 3; i++)
			memcpy(data + 18 + i * USB_DT_ENDPOINT_SIZE, &es2_endpoints[i], USB_DT_ENDPOINT_SIZE);
		reply_length = 18 + 3 * USB_DT_ENDPOINT_SIZE;
	} else if (ctrl->bRequest == USB_REQ_SET_CONFIGURATION) {
		arpc_in_endpoint = ioctl(raw_gadget_fd, USB_RAW_IOCTL_EP_ENABLE, &es2_endpoints[1]);
		cport_out_endpoint = ioctl(raw_gadget_fd, USB_RAW_IOCTL_EP_ENABLE, &es2_endpoints[2]);
		cport_in_endpoint = ioctl(raw_gadget_fd, USB_RAW_IOCTL_EP_ENABLE, &es2_endpoints[0]);
		ioctl(raw_gadget_fd, USB_RAW_IOCTL_CONFIGURE, 0);
		raw_gadget_io(USB_RAW_IOCTL_EP0_READ, 0, data, 0);
		return;
	}
	if (reply_length < 0)
		ioctl(raw_gadget_fd, USB_RAW_IOCTL_EP0_STALL, 0);
	else
		raw_gadget_io(USB_RAW_IOCTL_EP0_WRITE, 0, data,
			      reply_length < ctrl->wLength ? reply_length : ctrl->wLength);
}

static void *ep0_event_pump(void *unused)
{
	struct {
		struct usb_raw_event event;
		unsigned char data[MAX_TRANSFER];
	} buffer;

	for (;;) {
		buffer.event.type = 0;
		buffer.event.length = MAX_TRANSFER;
		if (ioctl(raw_gadget_fd, USB_RAW_IOCTL_EVENT_FETCH, &buffer) < 0)
			return NULL;
		if (buffer.event.type == USB_RAW_EVENT_CONTROL)
			handle_control_request((struct usb_ctrlrequest *)buffer.event.data);
	}
}

static void send_to_host(uint16_t operation_id, uint8_t type, uint8_t host_cport,
			 const void *payload, int payload_length)
{
	unsigned char message[MAX_TRANSFER];
	struct greybus_message_header *header = (void *)message;

	memset(header, 0, sizeof(*header));
	header->size = sizeof(*header) + payload_length;
	header->operation_id = operation_id;
	header->type = type;
	header->host_cport = host_cport;
	memcpy(message + sizeof(*header), payload, payload_length);
	raw_gadget_io(USB_RAW_IOCTL_EP_WRITE, cport_in_endpoint, message, header->size);
}

static int response_payload(const struct greybus_message_header *request, unsigned char *payload)
{
	memset(payload, 0, MAX_TRANSFER);
	if (request->host_cport == GB_SVC_CPORT) {
		switch (request->type) {
		case GB_SVC_TYPE_DME_PEER_GET:
			payload[2] = 0x26;
			payload[3] = 0x01;
			return 6;
		case GB_SVC_TYPE_DME_PEER_SET:
			return 2;
		case GB_SVC_TYPE_INTF_VSYS_ENABLE:
		case GB_SVC_TYPE_INTF_REFCLK_ENABLE:
		case GB_SVC_TYPE_INTF_UNIPRO_ENABLE:
			return 1;
		case GB_SVC_TYPE_INTF_ACTIVATE:
			payload[1] = GB_SVC_INTF_TYPE_GREYBUS;
			return 2;
		}
		return 0;
	}
	switch (request->type) {
	case GB_CONTROL_TYPE_VERSION:
		return 2;
	case GB_CONTROL_TYPE_GET_MANIFEST_SIZE:
		payload[0] = sizeof(module_manifest);
		return 2;
	case GB_CONTROL_TYPE_GET_MANIFEST:
		memcpy(payload, module_manifest, sizeof(module_manifest));
		return sizeof(module_manifest);
	case GB_CONTROL_TYPE_BUNDLE_ACTIVATE:
		return 1;
	}
	return 0;
}

static void make_cpu0_kworkers_sched_idle(void)
{
	struct sched_param param = { 0 };
	DIR *proc = opendir("/proc");
	struct dirent *entry;
	char path[300], comm[64];
	int fd;

	while ((entry = readdir(proc))) {
		snprintf(path, sizeof(path), "/proc/%s/comm", entry->d_name);
		fd = open(path, O_RDONLY);
		if (fd < 0)
			continue;
		if (read(fd, comm, sizeof(comm)) > 10 && !strncmp(comm, "kworker/0:", 10))
			sched_setscheduler(atoi(entry->d_name), SCHED_IDLE, &param);
		close(fd);
	}
	closedir(proc);
}

static void emulate_es2_svc_and_module(void)
{
	static const unsigned char protocol_version[2] = { 0, 1 };
	static const unsigned char hello[3] = { 0, 0, 1 };
	static const unsigned char module_inserted[4] = { 2, 1, 0, 0 };
	unsigned char message[MAX_TRANSFER], payload[MAX_TRANSFER];
	struct greybus_message_header *header = (void *)message;
	struct usb_raw_init init;
	pthread_t ep0_thread;

	raw_gadget_fd = open("/dev/raw-gadget", O_RDWR);
	memset(&init, 0, sizeof(init));
	strcpy((char *)init.driver_name, "dummy_udc");
	strcpy((char *)init.device_name, "dummy_udc.0");
	init.speed = USB_SPEED_HIGH;
	ioctl(raw_gadget_fd, USB_RAW_IOCTL_INIT, &init);
	ioctl(raw_gadget_fd, USB_RAW_IOCTL_RUN, 0);
	pthread_create(&ep0_thread, NULL, ep0_event_pump, NULL);
	while (cport_in_endpoint < 0)
		usleep(10000);

	send_to_host(1, GB_SVC_TYPE_PROTOCOL_VERSION, GB_SVC_CPORT, protocol_version, 2);
	send_to_host(2, GB_SVC_TYPE_SVC_HELLO, GB_SVC_CPORT, hello, 3);
	send_to_host(3, GB_SVC_TYPE_MODULE_INSERTED, GB_SVC_CPORT, module_inserted, 4);

	for (;;) {
		raw_gadget_io(USB_RAW_IOCTL_EP_READ, cport_out_endpoint, message, MAX_TRANSFER);
		if (header->type & GB_TYPE_RESPONSE)
			continue;
		if (header->type == GB_REQUEST_TYPE_CPORT_SHUTDOWN)
			return;
		usleep(2000);
		send_to_host(header->operation_id, header->type | GB_TYPE_RESPONSE, header->host_cport,
			     payload, response_payload(header, payload));
	}
}

int main(void)
{
	int fd;

	fd = open("/sys/devices/system/cpu/cpu1/online", O_WRONLY);
	write(fd, "0", 1);
	close(fd);

	if (fork() == 0) {
		emulate_es2_svc_and_module();
		make_cpu0_kworkers_sched_idle();
		_exit(0);
	}
	wait(NULL);
	sleep(3);
	return 0;
}
