#ifndef lint
static char *RCSid = "$Header: /usr/brule/guest/empire/empire/emprcs/client/termio.c,v 2.1 1995/10/11 03:07:43 empire Exp $";
#endif /* not lint */

/*
 * termio.c
 */

#include <stdio.h>
#include <sys/types.h>
#if defined(aix) || defined(hpux) || defined(sgi) || defined(linux)
#include <sys/termio.h>
#else
#include <sgtty.h>
#endif
#include "misc.h"

int
termio(fd, sock, auxfi)
	int	fd;
	int	sock;
	FILE	*auxfi;
{
	s_char	buf[4096];
	int	n;
	s_char	*ptr;
	int	nbytes;

	n = read(fd, buf, sizeof(buf));
	if (n == 0) {
		sendeof(sock);
		return 0;
	}
	if (n < 0) {
		perror("read standard input");
		return 0;
	}
	if (auxfi) {
	    fwrite(buf, n, 1, auxfi);
	}
	ptr = buf;
	while (n > 0) {
		nbytes = write(sock, ptr, n);
		if (nbytes <= 0) {
			perror("write server socket");
			return 0;
		}
		ptr += nbytes;
		n -= nbytes;
	}
	return 1;
}

sendeof(sock)
	int	sock;
{
	if (write(sock, "ctld\n", 5) < 5) {
		fprintf(stderr, "sendeof: EOF send failed\n");
		close(sock);
		return 0;
	}
	return 1;
}

int	echomode = 1;

#if defined(hpux) || defined(aix) || defined (sgi) || defined(linux) || defined (SVR4)
_noecho(fd)
	int	fd;
{
	struct	termio io;

	echomode = 0;
	(void) ioctl(fd, TCGETA, &io);
	io.c_line |= ECHO;
	(void) ioctl(fd, TCSETA, &io);
}

void
_echo(fd)
	int	fd;
{
	struct	termio io;

	if (echomode)
		return;
	(void) ioctl(fd, TCGETA, &io);
	io.c_line &= ~ECHO;
	(void) ioctl(fd, TCSETA, &io);
	echomode++;
}

#else

_noecho(fd)
	int	fd;
{
	struct	sgttyb sgbuf;

	echomode = 0;
	(void) ioctl(fd, TIOCGETP, &sgbuf);
	sgbuf.sg_flags &= ~ECHO;
	(void) ioctl(fd, TIOCSETP, &sgbuf);
}

_echo(fd)
	int	fd;
{
	struct	sgttyb sgbuf;

	if (echomode)
		return;
	(void) ioctl(fd, TIOCGETP, &sgbuf);
	sgbuf.sg_flags |= ECHO;
	(void) ioctl(0, TIOCSETP, &sgbuf);
	echomode++;
}
#endif
