
/*
 * ttym.c -- miscellaneous routines
 *
 * $Id$
 */

#include <h/nmh.h>
#include <pwd.h>

#ifndef	NSIG
# include <signal.h>
#endif	NSIG

#include <sys/time.h>

static int  ttyf ();

static
ttym (int fd, char *command, char *line, char *user, char **vec)
{
    RETSIGTYPE (*pstat) ();
    char *ap, *term, *myself;
    char *getlogin(), *ttyname();
    struct passwd *pw;

    if ((term = ap = ttyname (2)) && (term = strrchr(term, '/')))
	term++;
    if (term == NULL || *term == NULL)
	term = ap;
    if ((myself = getlogin ()) == NULL || *myself == NULL)
	myself = (pw = getpwuid (getuid ())) ? pw->pw_name : NULL;

    pstat = SIGNAL (SIGPIPE, SIG_IGN);
    write (fd, command, strlen (command));
    write (fd, "", 1);

    if (term)
	write (fd, term, strlen (term));
    write (fd, "", 1);

    if (myself)
	write (fd, myself, strlen (myself));
    write (fd, "", 1);

    if (line && *line)
	write (fd, line, strlen (line));
    write (fd, "", 1);

    if (user && *user)
	write (fd, user, strlen (user));
    write (fd, "", 1);

    if (vec)
	while (ap = *vec++) {
	    write (fd, ap, strlen (ap));
	    write (fd, "", 1);
	}

    write (fd, "", 1);
    SIGNAL (SIGPIPE, pstat);
}


static int
ttyv (int fd)
{
    int ifds, nbits;
    char c;
    struct timeval tv;

    ifds = 1 << fd;
    nbits = getdtablesize();
    tv.tv_sec = SMLWAIT;
    tv.tv_usec = 0;
    if (select (nbits, &ifds, (int *) 0, (int *) 0, &tv) <= 0
	    || read (fd, &c, 1) != 1)
	return NOTOK;
    if (c == NULL)
	return fd;
    putc (c, stderr);

    ttyf (fd, stderr);
    return NOTOK;
}


static int
ttyf (int fd, FILE *f)
{
    int i;
    char buffer[BUFSIZ];

    while ((i = read (fd, buffer, sizeof buffer)) > 0)
	fwrite (buffer, sizeof (char), i, f);
    return i;
}

