/* anders@brander.dk 2001-03-06 */

#define HOST_ADDR "sunsite.dk"
#define HOST_PORT 37
#define EPOCH_DIFFERENCE 2208988800

#include <winsock.h>
#include <windows.h>
#include <time.h>
#include <stdio.h>

void bail(char *);
time_t getTimeFromHost(char *);

time_t
getTimeFromHost(char *hostname)
{
	struct sockaddr_in buh;
	struct hostent *hp;
	SOCKET b;

	if ((hp = gethostbyname(hostname)) == NULL)
	{
		return(-1);
	}

	memset(&buh,0,sizeof(buh));
	memcpy((char *)&buh.sin_addr,hp->h_addr,hp->h_length);
	buh.sin_family= hp->h_addrtype;
	buh.sin_port= htons((u_short) HOST_PORT );

	if ((b = socket(hp->h_addrtype,SOCK_STREAM,0)) == INVALID_SOCKET)
		return(-1);

	if (connect(b, (struct sockaddr *) &buh, sizeof(buh)) < 0)
	{
		closesocket(b);
		return(-1);
	}

	unsigned long timebuff;
	if (recv(b, (char *) &timebuff, 4, 0) != 4)
	{
		closesocket(b);
		return(-1);
	}
	closesocket(b);

	return((time_t) ntohl(timebuff));
}

int WINAPI
WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	WSADATA wsaData;

	if (WSAStartup(MAKEWORD( 1, 1 ), &wsaData ))
		bail("WSAStartup() failed");

	SYSTEMTIME systime;
	time_t n = getTimeFromHost(HOST_ADDR)-EPOCH_DIFFERENCE;
	struct tm *bah;
	bah = localtime(&n);

	systime.wYear = bah->tm_year+1900;
	systime.wMonth = bah->tm_mon+1;
	systime.wDay = bah->tm_mday;
	systime.wHour = bah->tm_hour;
	systime.wMinute = bah->tm_min;
	systime.wSecond = bah->tm_sec;

	if (!SetLocalTime(&systime))
		bail("SetLocalTime()");

	if (WSACleanup())
		bail("WSACleanup() failed");

	return(0);
}

void
bail(char *s)
{
	MessageBox(NULL, s, "Time client", MB_OK);
	exit(1);
}


