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

/*
 * dev_pty
 */
# include <stdio.h>
# include <stdlib.h>
# include <unistd.h>
# include <string.h>
# include <fcntl.h>
# include <errno.h>
# include <sys/types.h>
# include <sys/socket.h>
# include <sys/wait.h>
# include <netinet/in.h>
# include <signal.h>
# include <stdarg.h>
# include <termios.h>
# include <stdarg.h>
# include <begemot.h>

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

RCSID("$Id: tty_pty.c 468 2001-03-01 12:03:47Z hbb $")

void		open_pty(void);

int	master;			/* master side of pty */
int	slave;			/* slave side of pty */
char	Sc[3] = "p0";		/* slave name */
char	**args;			/* pointer to args to be passed to xterm */
int	cs7;


static char usgtxt[] =
"Begemot PDP11 emulator Version %s; Terminal-to-pty adapter\n"
"Copyright (c) 1994-2000 Begemot Computer Associates. All rights reserved.\n"
"Usage: tty_pty [-7]\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);
}


int
main(int argc, char *argv[])
{
	int	opt;
	struct termios t;

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

		  case 'h':
			usage(0);

		  case '7':
			cs7 = 1;
			break;
		}

	tty_init();

	if(setsid() < 0) {
		error("setsid: %s", strerror(errno));
		Exit(5);
	}

	catch_signal(SIGCHLD, onsig);

	open_pty();

	tcgetattr(slave, &t);
	cfmakeraw(&t);
	tcsetattr(slave, TCSANOW | TCSASOFT, &t);

	tcgetattr(master, &t);
	cfmakeraw(&t);
	tcsetattr(master, TCSANOW | TCSASOFT, &t);

# if 0
	close(slave);
# endif

	fprintf(stderr, "/dev/pty%s on %d/%d\n", Sc, master, slave);

# if 0
	if(fcntl(master, F_SETFL, O_NONBLOCK)) {
		error("fcntl: can't set master to non-block: %s", strerror(errno));
		Exit(5);
	}

	if(fcntl(0, F_SETFL, O_NONBLOCK)) {
		error("fcntl: can't set sock to non-block: %s", strerror(errno));
		Exit(4);
	}
# endif

	tty_loop(master);

	return 0;
}

void
process_input()
{
}

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


void
Exit(int e)
{
	exit(e);
}



/*
 * find a free pty, open both sides for r/w and
 * set globl master and slave and Sc to the 2 variable chars in the pty name
 * panic if no pty free
 */
void
open_pty(void)
{
	char	pty[] = "/dev/ptyp0";
	char	*c1, *c2 = "keep compiler happy";

	for(c1 = "pr"; *c1; c1++) {
		for(c2 = "0123456789abcdef"; *c2; c2++) {
			sprintf(pty, "/dev/pty%c%c", *c1, *c2);
			if((master = open(pty, O_RDWR)) >= 0)
			goto open_slave;
		}
	}
	error("could not open any pty\n");
	Exit(10);

 open_slave:

	sprintf(pty, "/dev/tty%c%c", *c1, *c2);
    
	if((slave = open(pty, O_RDWR)) < 0) {
		error("can't open slave: %s - %s\n", pty, strerror(errno));
		Exit(11);
	}

	Sc[0] = *c1;
	Sc[1] = *c2;
}


void
process_end()
{
}
