#include "config.h"
#include <assert.h>
#include <common/amount.h>
#include <common/memleak.h>
#include <ccan/io/io.h>
#include <ccan/read_write_all/read_write_all.h>
#include <wire/wire.h>

/* We don't want to actually do io! */
#define write my_write
#define read my_read
#define write_all my_write_all
#define read_all my_read_all

static char *my_rbuf, *my_wbuf;
static size_t my_rbuf_off;

static ssize_t my_read(int fd, void *buf, size_t count)
{
	if (strlen(my_rbuf + my_rbuf_off) < count)
		count = strlen(my_rbuf + my_rbuf_off);
	memcpy(buf, my_rbuf + my_rbuf_off, count);
	my_rbuf_off += count;
	return count;
}
static bool my_read_all(int fd, void *buf, size_t count)
{
	my_read(fd, buf, count);
	return true;
}

static ssize_t my_write(int fd, const void *buf, size_t count)
{
	size_t buflen = tal_bytelen(my_wbuf);
	tal_resize(&my_wbuf, buflen + count);
	memcpy(my_wbuf + buflen, buf, count);
	return count;
}
static bool my_write_all(int fd, const void *buf, size_t count)
{
	my_write(fd, buf, count);
	return true;
}

int websocket_main(int argc, char *argv[]);

#define main websocket_main
  #include "../websocketd.c"
  #include "../sha1.c"
#undef main

/* AUTOGENERATED MOCKS START */
/* AUTOGENERATED MOCKS END */

int main(int argc, char *argv[])
{
	const char *hdr;

	common_setup(argv[0]);

	hdr = "GET /chat HTTP/1.1\r\n"
		"Host: server.example.com\r\n"
		"Upgrade: websocket\r\n"
		"Connection: Upgrade\r\n"
		"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
		"Origin: http://example.com\r\n"
		"Sec-WebSocket-Protocol: chat, superchat\r\n"
		"Sec-WebSocket-Version: 13\r\n\r\n";

	my_rbuf = tal_strdup(tmpctx, hdr);
	my_wbuf = tal_arr(tmpctx, char, 0);

	http_upgrade(STDIN_FILENO);
	assert(streq(tal_strndup(tmpctx, my_wbuf, tal_bytelen(my_wbuf)),
		     "HTTP/1.1 101 Switching Protocols\r\n"
		     "Upgrade: websocket\r\n"
		     "Connection: Upgrade\r\n"
		     "Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n"
		     "\r\n"));

	common_shutdown();
}
