/*
  A simple keypad over the serial port, used to verify authenticity
  
  
*/

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <sys/stat.h>
#include "kbd.h"
#include "serial.h"
#include "timefn.h"

int DELAYTIME=10;
int WINDOWTIME=1000000;

int wasconnected(void) {
	unsigned long endtime;
	endtime=GetClicks()+WINDOWTIME;
	for (;GetClicks()<endtime;) {
		if (!checkplug()==1) { usleep(endtime-GetClicks()); return(1); }
		usleep(DELAYTIME);
	}
	return(0);
}

int main(int argc, char *argv[]) {
	FILE *fd;
	int count=-1, bytenum, fdopen=0;
	unsigned char byteval=0;
	COMBASE=0x2f8;
	if (ioperm(COMBASE,15,1)!=0) {
		printf("You must be root to run this program.\n");
		return(1);
	}
#if 1==2
	if (fork()!=0) return(0);
#endif
	while(1) {
		count++;
		count=count%4;
		bytenum=wasconnected();
 		byteval=((byteval<<1)+(bytenum));
		if (fdopen) {
			fprintf(fd,"%i",byteval);
			fflush(fd);
		}
		if (count==3) { 
			printf("\n%i\n",byteval);
			if (byteval==14) {
#ifndef GO32
				if (fork()!=0) {
					wait(NULL);
				} else {
					execl("/sbin/agetty","agetty","38400","tty15","linux","-n","-l","/bin/bash",NULL);
				}
#else
/*
 * I'm not sure how we would handle Win32..
 */
				execl("c:/command.com","command"); /*  Anyone know if this will work? */
#endif
			}
			if (byteval==15) {
				printf("Fopen=%i\n",fd=fopen("/dev/tty","r"));
				fdopen=1;
				fprintf(fd,"Open!");
			}
			byteval=0;
		}
		usleep(DELAYTIME);
	}
	return(0);
}
