/*
 * $Copyright:	$
 * Copyright (c) 1984, 1985, 1986, 1987, 1988, 1989, 1990 
 * Sequent Computer Systems, Inc.   All rights reserved.
 *  
 * This software is furnished under a license and may be used
 * only in accordance with the terms of that license and with the
 * inclusion of the above copyright notice.   This software may not
 * be provided or otherwise made available to, or used by, any
 * other person.  No title to or ownership of the software is
 * hereby transferred.
 *
 */

/*	Copyright (c) 1984 AT&T	*/
/*	  All Rights Reserved  	*/

/*	THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF AT&T	*/
/*	The copyright notice above does not evidence any   	*/
/*	actual or intended publication of such source code.	*/

#ident	"$Header: mesg.c 1.5 89/11/14 $@(#)mesg:mesg.c	1.2"

/*
 * mesg -- set current tty to accept or
 *	forbid write permission.
 *
 *	mesg [-y] [-n]
 *		y allow messages
 *		n forbid messages
 *	return codes
 *		0 if messages are ON or turned ON
 *		1 if messages are OFF or turned OFF
 *		2 if usage error
 */

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>

struct stat sbuf;

char *tty;
char *ttyname();

main(argc, argv)
char *argv[];
{
	int i, c, r=0, errflag=0;
	extern int optind;

	for(i = 0; i <= 2; i++) {
		if ((tty = ttyname(i)) != NULL)
			break;
	}
	if (stat(tty, &sbuf) < 0)
		error(gettxt("mesg:1", "cannot stat"));
	if (argc < 2) {
		if (sbuf.st_mode & 02)
			printf(gettxt("mesg:2", "is y\n"));
		else  {
			r = 1;
			printf(gettxt("mesg:3", "is n\n"));
		}
	}
	while ((c = getopt(argc, argv, "yn")) != EOF) {
		switch (c){
		case 'y':
			newmode(0622);
			break;
		case 'n':
			newmode(0600);
			r = 1;
			break;
		case '?':
			errflag++;
		}
	}

	if (errflag /*  || (argc > optind) */ )
		error(gettxt("mesg:4", "usage: mesg [-y] [-n]"));

/* added for temporary compat. */
	if(argc > optind) switch(*argv[optind]) {
		case 'y':
			newmode(0622);
			break;
		case 'n':
			newmode(0600);
			r = 1;
			break;
		default:
			errflag++;
		}

	if (errflag)
		error(gettxt("mesg:4", "usage: mesg [-y] [-n]"));
/* added to here */
	exit(r);
}

error(s)
char *s;
{
	fprintf(stderr, gettxt("colon:36", "mesg: %s\n"), s);
	exit(2);
}

newmode(m)
{
	if (chmod(tty, m) < 0)
		error(gettxt("mesg:5", "cannot change mode"));
}
