#include	<stdio.h>
#include	<signal.h>

/*
 *	attach/detach ttyname [...]
 *
 *	Turn terminals on and off by changing ttys file and signalling init
 */

#define		TTYS		32

extern	char	*concat();

char	tfile[ ]	=	"/etc/ttys";
char	fmt[ ]		=	"%c%c%s\n";
char	*names[TTYS];
char	name[32];				/* tty name */
char	ad;					/* attach/detach flag */
char	br;					/* baud rate */


main(argc, argv)
char **argv;
{
	register FILE *in, *out;
	register int  nttys;
	register char *p;
	register char set;
	register int  found;
	register int  i;

	if (argc <= 1)
		error("Usage: %s tty-name ...\n", *argv);

	if ((in  = fopen(tfile, "r")) == NULL)
		error("Can't open %s\n", tfile);

	if ((out = fopen(tfile, "a")) == NULL)
		error("Can't re-write %s\n", tfile);

	rewind(out);


	/* Determine which name command was called by */
	for (p = *argv; *p; p++)
		;
	while (p >= *argv && *p != '/')
		p--;

	/* Character to update tty file with */
	set = (p[1] == 'd'  ?  '0' : '1');


	/* Set tty names into tmp list */
	nttys = 0;
	while (--argc)
		if (nttys < TTYS)
			names[nttys++] = *(++argv);

	while (fscanf(in, fmt, &ad, &br, name) != EOF)  {

		found = 0;

		/* Try the terminal names */
		for (i=0; i<nttys; i++)
			if (cmp(name, names[i]))  {
				fprintf(out, fmt, set, br, name);
				found++;
				break;
				}

		if (found)
			continue;

		/* Try the string ttyname */
		for (i=0; i<nttys; i++)
			if (cmp(name, concat("tty", names[i])))  {
				fprintf(out, fmt, set, br, name);
				found++;
				break;
				}

		if (found)
			continue;

		/* Not found in list */
		fprintf(out, fmt, ad, br, name);
		}

	fflush(out);
	fclose(out);
	fclose(in);

	/* Signal initialisation process */
	if (kill(1, SIGINT) < 0)
		error("Can't signal init process\n", 0);

	return(0);
}


error(s, x)
register char *s;
register int   x;
{
	fprintf(stderr, s, x);
	exit(1);
}


char	*concat(s1, s2)
register char *s1, *s2;
{
	register char *s;
	static	 char buf[64];

	s = &buf[0];
	while (*s1)
		*s++ = *s1++;

	do
		*s++ = *s2;
		while (*s2++);

	return(&buf[0]);
}



cmp(s1, s2)
register char *s1, *s2;
{
	while (*s1 == *s2)  {
		if (*s1 == '\0')
			return(1);

		s1++;
		s2++;
		}

	return(0);
}
