/* Internet Time server
 * Copyright 1993 Mark Turner, G7LEU mt@kram.org
 *
 * ATARI Version by David Nash - dnash@chaos.demon.co.uk
 *
 * don't swap bytes to little endian order 
 */
#include <stdio.h>
#include <string.h>
#include "global.h"
#include "mbuf.h"
#include "socket.h"
#include "session.h"
#include "proc.h"

static int Stime = -1;

static void __stdargs timed __ARGS((int s,void *unused,void *p));

int	timestart(int argc, char *argv[], void *p);
int	time0(int argc, char *argv[], void *p);

/* Start up time service */
int
timestart(argc,argv,p)
int argc;
char *argv[];
void *p;
{
	struct sockaddr_in lsocket;
	int s;

	if(Stime != -1){
		return 0;
	}
	psignal(Curproc,0);	/* Don't keep the parser waiting */
	chname(Curproc,"Time listener");

	lsocket.sin_family = AF_INET;
	lsocket.sin_addr.s_addr = INADDR_ANY;
	if(argc < 2)
		lsocket.sin_port = IPPORT_TIME;
	else
		lsocket.sin_port = atoi(argv[1]);

	Stime = socket(AF_INET,SOCK_STREAM,0);
	bind(Stime,(char *)&lsocket,sizeof(lsocket));
	listen(Stime,1);
	for(;;){
		if((s = accept(Stime,NULLCHAR,(int *)NULL)) == -1)
			break;	/* Service is shutting down */

		/* Spawn a server */
		newproc("timed",512,timed,s,NULL,NULL,0);
	}
	return 0;
}

static void
__stdargs timed(s,unused,p)
int s;
void *unused;
void *p;
{
#ifndef ATARI	
	char t;
#endif
	union
		{
		time_t time;
		char bytes[sizeof (time_t)];
		} result;
	sockmode(s,SOCK_ASCII);
	sockowner(s,Curproc);
	result.time = time(NULL);
	result.time += 2208988800L;
#ifndef ATARI								
	t = result.bytes[0];					/* swap to little endian format for pc */
	result.bytes[0] = result.bytes[3];
	result.bytes[3] = t;
	t = result.bytes[1];
	result.bytes[1] = result.bytes[2];
	result.bytes[2] = t;
#endif
	send(s,result.bytes,sizeof (time_t),0);
	close_s(s);
}

int
time0(argc,argv,p)
int argc;
char *argv[];
void *p;
{
	close_s(Stime);
	Stime = -1;
	return 0;
}
