/*
 * tntp/tntpd
 *
 * A term client to set the local time to the remote time.
 * Can be run once as tntp or as a daemon tntpd
 *
 * (C) 1994 Kevin Lentin (kevinl@cs.monash.edu.au)
 *
 */

#define I_ERRNO
#define I_SYS
#define I_SOCKET
#define I_STRING
#include "includes.h"

#include "client.h"

#define STAT(local, st) \
	if (send_command(s, C_STATS, local, "%d",st)< 0) { \
		fprintf(stderr,"C_STATS command failed. Abort.\n"); \
		exit(1); \
	}

#define VERBOSE if(verbose)printf

long delay = 300;
int verbose = 0;

static int local_options ( char opt, char *optarg )
{
  switch(opt)
  {
  case 'd' :
    printf("optarg=%s\n", optarg);
    delay = atoi(optarg);
	if (delay < 10) {
		fprintf(stderr, "Minimum delay is 10 seconds\n");
		return -1;
	}
	VERBOSE("Delay set to %d seconds\n", delay);
    break;
  case 'v' :
    verbose = 1;
	break;
  default:
    return -1;
  }
  return 0;
}

void main(int argc, char *argv[])
{
	int s;
	int first;
	int daemon = 0;
	struct timeval t1,t2,t;
	long diff;
	char args[10];

	strcpy(args,"v");
	if (argv[0][strlen(argv[0])-1] == 'd') {
		daemon = 1;
		strcat(args,"d:");
	}

	priority = 10; /* We want immediate results */
	first = client_options(argc,argv,args, local_options);
	if (first == -1 || first > argc)
		exit (1);
	setbuf(stderr, 0);

	while (1) {
		if ((s = connect_server(term_server)) <0)
		{
			/* Move above later */
			if (daemon)
				continue; /* Continues the while */
			perror("Couldn't open term");
			close(s);
			exit(1);
		}
#ifdef SVR4
		gettimeofday(&t1);
#else
		gettimeofday(&t1, (struct timezone *) 0 );
#endif
		VERBOSE("Our time is: %ld %ld\n", t1.tv_sec, t1.tv_usec);
		STAT(0,-9);
		VERBOSE("Got result:%s:\n", command_result);
		sscanf(command_result, "%ld %ld", &t.tv_sec, &t.tv_usec);
#ifdef SVR4
		gettimeofday(&t2);
#else
		gettimeofday(&t2, (struct timezone *) 0 );
#endif
		VERBOSE("Our time is: %ld %ld\n", t2.tv_sec, t2.tv_usec);
		diff = (t2.tv_sec - t1.tv_sec) * 1000000 + t2.tv_usec - t1.tv_usec;
		VERBOSE("Diff = %ld\n", diff);
		t.tv_usec += diff;
		t.tv_sec += (t.tv_usec / 1000000);
		t.tv_usec %= 1000000;

		VERBOSE("Setting time to: %ld %ld\n", t.tv_sec, t.tv_usec);
#ifdef SVR4
		settimeofday(&t);
#else
		settimeofday(&t, (struct timezone *) 0 );
#endif
		
		close(s);
		if (!daemon)
			break;
		sleep(delay);
	}
}
