/* 
 * txUtmp.c --
 *
 *	This file contains procedures (stolen from Xterm and other places)
 *	for creating and deleting entries in /etc/utmp.
 *
 * Copyright 1987 Regents of the University of California
 * Permission to use, copy, modify, and distribute this
 * software and its documentation for any purpose and without
 * fee is hereby granted, provided that the above copyright
 * notice appear in all copies.  The University of California
 * makes no representations about the suitability of this
 * software for any purpose.  It is provided "as is" without
 * express or implied warranty.
 */

#ifndef lint
static char rcsid[] = "$Header: /sprite/src/lib/mx/RCS/txUtmp.unix,v 1.5 89/05/19 17:26:00 ouster Exp $ SPRITE (Berkeley)";
#endif not lint


#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <sys/file.h>
#include <sys/types.h>
#include <ttyent.h>
#include <utmp.h>
#include <pwd.h>


/*
 *----------------------------------------------------------------------
 *
 * UtmpEntry --
 *
 *	Add or delete an entry for this pty in /etc/utmp.
 *
 * Results:
 *	0 is returned if all went well, -1 if /etc/utmp couldn't
 *	be written.
 *
 * Side effects:
 *	If "io" is TRUE, a new entry gets added to /etc/utmp.  Otherwise,
 *	the entry for this pty gets removed.  This code was stolen from
 *	xterm.
 *
 *----------------------------------------------------------------------
 */

int
TxUtmpEntry(io, ttydev, display)
    int io;			/* TRUE means add entry, FALSE means remove. */
    char *ttydev;		/* Name of the pty, e.g. "/dev/ttyp0". */
    char *display;		/* Name of the display, e.g. "unix:0" or
				 * "ucbarpa". */
{
    struct utmp ut;
    struct ttyent *ty;
    register int s;
    long slot;
    int ufd;
    struct passwd *pw;

    pw = getpwuid(getuid());
    if (!pw) {
	return(0);
    }

    if (io == 1) {
	strncpy(ut.ut_line, &ttydev[5], sizeof ut.ut_line);
	strncpy(ut.ut_host, display, sizeof ut.ut_host);
	strncpy(ut.ut_name, pw->pw_name, sizeof ut.ut_name);
	(void) time((time_t *) &ut.ut_time);
    } else {
	strcpy(ut.ut_line, "");
	strcpy(ut.ut_name, "");
	strcpy(ut.ut_host, "");
	ut.ut_time = 0;
	chown(ttydev, 0, 0);
	chmod(ttydev, 0666);
    }


    setttyent();
    slot = 0;
    s = 0;
    for (ty = getttyent(); ty != 0; ty = getttyent()) {
	s++;
	if (strcmp(ty->ty_name, &ttydev[5]) == 0) {
	    slot = s;
	    break;
	}
    }
    endttyent();
    if (slot > 0) {
	ufd = open("/etc/utmp", O_WRONLY, 0);
	if (ufd >= 0) {
	    if (lseek(ufd, slot * sizeof ut, 0) < 0L ||
		    write(ufd, (char *)&ut, sizeof ut) != sizeof ut) {
		close(ufd);
		return(-1);
	    }
	}
	close(ufd);
    }
    return(0);
}
