/*
 * frankensocket - tiny socket compatibility layer for liveside.
 *
 * This header keeps the common BSD socket vocabulary visible on POSIX and
 * Win32 while naming the unavoidable differences explicitly.
 */
#ifndef FRANKENSOCKET_H
#define FRANKENSOCKET_H

#include <stddef.h>
#include <stdio.h>
#include <string.h>

#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#pragma comment(lib, "ws2_32.lib")

typedef int FrankenSockError;

static int
frankensocket_startup(void)
{
	WSADATA wsa;

	if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
		fprintf(stderr, "[liveside] WSAStartup failed\n");
		return -1;
	}
	return 0;
}

static void
frankensocket_cleanup(void)
{
	WSACleanup();
}

static void
frankensocket_ignore_sigpipe(void)
{
}

static FrankenSockError
frankensocket_error(void)
{
	return WSAGetLastError();
}

static void
frankensocket_perror(const char *msg)
{
	fprintf(stderr, "%s: WSA error %d\n", msg, frankensocket_error());
}

static int
frankensocket_close(SOCKET s)
{
	return closesocket(s);
}

static long
frankensocket_send(SOCKET s, const void *buf, size_t len)
{
	return send(s, (const char *)buf, (int)len, 0);
}

static long
frankensocket_recv(SOCKET s, void *buf, size_t len)
{
	return recv(s, (char *)buf, (int)len, 0);
}

#else
#include <errno.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <signal.h>
#include <sys/socket.h>
#include <unistd.h>

typedef int SOCKET;
typedef int FrankenSockError;

#ifndef INVALID_SOCKET
#define INVALID_SOCKET (-1)
#endif

static int
frankensocket_startup(void)
{
	return 0;
}

static void
frankensocket_cleanup(void)
{
}

static void
frankensocket_ignore_sigpipe(void)
{
	signal(SIGPIPE, SIG_IGN);
}

static FrankenSockError
frankensocket_error(void)
{
	return errno;
}

static void
frankensocket_perror(const char *msg)
{
	fprintf(stderr, "%s: %s\n", msg, strerror(frankensocket_error()));
}

static int
frankensocket_close(SOCKET s)
{
	return close(s);
}

static long
frankensocket_send(SOCKET s, const void *buf, size_t len)
{
	return (long)send(s, buf, len, 0);
}

static long
frankensocket_recv(SOCKET s, void *buf, size_t len)
{
	return (long)recv(s, buf, len, 0);
}
#endif

#endif /* FRANKENSOCKET_H */
