/*
 *  enable.c
 *  copyright 1986 Maple Lawn Farm, Inc.
 * 
 *  drops/adds terminals from/to multi-user status
 *  usage: "enable ttyxx"  or  "disable ttyxx"
 *
 *  compile:  cc -O -s -o enable enable.c
 *  	      ln enable disable
 */

#include <stdio.h>
#include <signal.h>

#define	LEN	40
#define INIT	1			/* init is pid 1 */
#define TTYS	"/etc/ttys"
#define TMP	"/etc/ttys.tmpXXXXXX"

char	*mktemp();

main(argc, argv)
int  argc;
char **argv;
{
	char	**p, buf[LEN], *last, 
		*tmp = mktemp(TMP),
		set = (**argv=='d') ? '0': '1';
	int	i, change = 0;
	static	int	(*sigs[NSIG-1])();

	if (!freopen(TTYS, "r", stdin))
		perror(TTYS), exit(1);
	if (!freopen(tmp, "w", stdout))
		perror(tmp), exit(1);

	while (fgets(buf, sizeof buf, stdin)) {
				/* use last char as tty id */
		last = buf + strlen(buf) - 1;
		*last = '\0';
				/* check argv for match */
		for (p = argv+1; *p; ++p)
			if (**p && !strcmp(last-strlen(*p), *p))
				break;
				/* check status in file */
		if (*p && buf[0] != set) {
			++change;
			buf[0] = set;
		}
		puts(buf);
	}

	if (change) {
				/* trap all interrupts */
		for (i=1; i<NSIG; ++i)
			if (i != SIGKILL)
				sigs[i-1] = signal(i, SIG_IGN);
		fflush(stdout);
				/* you're committed now */
		rename(TTYS, tmp);
				/* make init reread TTYS */
		if (kill(INIT, SIGINT) == -1)
			perror("init");
				/* let life go on */
		fputs("Please do not enable/disable for one minute.\n", 
			stderr);
		for (i=1; i<NSIG; ++i)
			if (i != SIGKILL)
				signal(i, sigs[i-1]);
		exit(1);
	}
	else {
		fputs("no change to /etc/ttys\n", stderr);
		unlink(tmp);
	}
}


rename(new,old)
char  *new, *old;
{
	unlink(new);
	if (link(old, new) == -1)
		perror(new), exit(1);
	if (unlink(old) == -1)
		perror(old), exit(1);
}
