/* Copyright (c)1994-2000 Begemot Computer Associates. All rights reserved.
 * See the file COPYRIGHT for details of redistribution and use. */

# include <stdio.h>
# include <stdlib.h>
# include <sys/types.h>
# include <sys/socket.h>
# include <errno.h>
# include <termios.h>
# include <signal.h>
# include <fcntl.h>
# include <unistd.h>
# include <string.h>
# include <begemot.h>

# include "cdefs.h"
# include "util.h"
# include "tty.h"


RCSID("$Id: tty_tty.c 444 2000-11-14 12:11:23Z hbb $")


int		cs7;
struct termios	saved;
int		issaved;
int		fd;


static char usgtxt[] =
"Begemot PDP11 emulator Version %s; Terminal-to-serial-line adapter\n"
"Copyright (c) 1994-2000 Begemot Computer Associates. All rights reserved.\n"
"Usage: tty_tty [-7] device\n"
"where:\n"
"	-7	mask to 7bits\n";

static void usage(int) DEAD_FUNC;

static void
usage(int e)
{
	fprintf(stderr, usgtxt, VERSION);
	exit(e);
}


void
Exit(int ex)
{
	if(issaved)
		tcsetattr(fd, TCSANOW | TCSASOFT, &saved);
	exit(ex);
}

/*
 * fd 0 is socket to parent
 */
int
main(int argc, char *argv[])
{
	struct termios t;
	int	opt;

	while((opt = getopt(argc, argv, "h7")) != EOF)
		switch(opt) {

		  case 'h':
			usage(0);

		  case '7':
			cs7 = 1;
			break;
		}
	argc -= optind;
	argv += optind;

	tty_init();

	if((fd = open(argv[0], 2)) < 0) {
		error("open(%s): %s", argv[0], strerror(errno));
		return errno;
	}
	if(setsid() < 0) {
		error("setsid(): %s", strerror(errno));
		return errno;
	}
	if(fcntl(fd, F_SETFL, O_NONBLOCK)) {
		error("fcntl(O_NONBLOCK): %s", strerror(errno));
		return errno;
	}

	catch_signal(SIGPIPE, onsig);

	tcgetattr(fd, &t);
	saved = t;
	issaved = 1;
	cfmakeraw(&t);
	tcsetattr(fd, TCSANOW | TCSASOFT, &t);

	tty_loop(fd);

	Exit(0);
}

void
process_output()
{
	if(cs7)
		makecs7();
}

void
process_input()
{
}
void
process_end()
{
}
