#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <fcntl.h>
#include <time.h>
#ifdef DOS
#include <alloc.h>
#endif
#ifdef UNIX
#include <sys/ioctl.h>
#include <sys/lock.h>
#else
#ifdef DOS
#include <dos.h>
#include <process.h>
#endif
#endif
#include "struct.h"
#include <setjmp.h>


jmp_buf errjmp;

/*
 *	main driver loop
 */


void Time_Alert()
{
	log_error("Watchdog timer alert\n");
	panic();
}

void End_Limit()
{
#ifdef SIGALRM
	alarm(0);
#endif
}

void Allow_Time(t)
long t;
{
#ifdef SIGALRM
	signal(SIGALRM,Time_Alert);
	alarm(t);
#endif
}

/*
 *	It all starts here.
 */

short Booted=0;

#ifdef DOS
int
#else
void
#endif
main(argc,argv)
int argc;
char *argv[];
{
	int debug=0;
	long to,tc;
	int fh;
#ifdef UNIX
	char *p;
#endif
/*
 *	Lock ourselves away if the yama_lock is set and we are run
 *	from inittab
 */
 #ifdef UNIX
	while(getppid()==1&&access("/usr/sysdev/yama/YAMA/yama_lock",0)==0)
		sleep(120);
	if(getppid()==1)
	{
		close(0);
		close(1);
		close(2);
		setpgrp(getpid(),0);
		if(open("yboot_log",O_RDWR|O_APPEND)==-1)
			open("/dev/null",O_RDWR);
		dup(0);
		dup(0);
	}
 #endif
 /*
 *	Init randoms and announce ourselves
 */
	srand(getpid());
	printf("YAMA 1.15, (c) 1990 Alan Cox.\n");
	printf("\
This software is provided free and without any warranty implied or otherwise\n\
See the file 'LICENSE' for details.\n");
	if(argv[1]&&strcmp(argv[1],"-d")==0)
	{
		debug=1;
		argv++;
		argc--;
	}
	else
	{
#ifdef UNIX
#ifdef SIGILL
		signal(SIGILL,GoSplat);
#endif
#ifdef SIGSEGV
		signal(SIGSEGV,GoSplat);
#endif
#ifdef SIGBUS
		signal(SIGBUS,GoSplat);
#endif
#ifdef SIGFPE
		signal(SIGFPE,GoSplat);	/* dorks dividing by zero.. hardly
					   floating point! */
#endif
#endif
	}
#ifdef SIGPIPE
	signal(SIGPIPE,SIG_IGN);	/* We cause these */
#endif
	if(!argv[1])
	{
		fprintf(stderr,"%s [-d] <DB_NAME>\n",argv[0]);
		exit(4);
	}
/*
 *	Load the game
 */
	if(Load_Database(argv[1],debug)!=0)
	{
		printf("[EXIT]: Abandoning.\n");
		exit(5);
	}
/*
 *	Commence IPC operations
 */
	if(Bind_To_Server()==0)
	{
		fprintf(stderr,"Server not responding... exiting.\n");
		exit(6);
	}
/*
 *	Get Real Time
 */
	time(&tc);
	fprintf(stderr,"Booted System\nRunning pid=%d\n",getpid());
	fflush(stderr);
	Booted=1;	/* From now on we shove errors into runtime */
	if(setjmp(errjmp))
	{
		/* we come here after a panic, panic has decided whether to
		   take a running jump.. we just do the work
		   currently all we do is...
		 */
		 ;
	}
	else
	{
		 /*
		  *	Run an initial table 6 cycle
		  */
		Exec_Time_Event();
	}
 /*
  *	The main loop
  */
	while(1)
	{
		time(&to);
		do
		{
			Allow_Time(60);		/* If your machine stops dead at times you might want to up this */
			Scan_Packets();
			End_Limit();
			time(&tc);
		}
		while(to==tc);	
		if(UsersActive()>0)
		{
			Allow_Time(60);
			Exec_Time_Event();
			End_Limit();
		}
	}
}