/*
 * $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	"@(#)libc-port:gen/ttyname.c	1.8"
/*	3.0 SID #	1.2	*/
/*LINTLIBRARY*/
/*
 * ttyname(f): return "/dev/ttyXX" which the the name of the
 * tty belonging to file f.
 *
 * This program works in two passes: the first pass tries to
 * find the device by matching device and inode numbers; if
 * that doesn't work, it tries a second time, this time doing a
 * stat on every file in /dev and trying to match device numbers
 * only. If that fails too, NULL is returned.
 */

#define	NULL	0
#include <sys/types.h>
#include <sys/param.h>
#include <sys/ufsinode.h>
/* #include <sys/ufsdir.h> */
#include <sys/stat.h>
#include <sys/dir.h>
#include <dirent.h>

extern int open(), read(), close(), stat(), fstat(), isatty();
extern char *strcpy(), *strcat();
extern char *dev_to_ttyname();

static char rbuf[MAXNAMLEN+1], dev[]="/dev/", *rbufptr;

char *
ttyname(f)
int	f;
{
	struct stat fsb, tsb;
	struct dirent *db;
	DIR *dir = NULL;
	register int pass1;

	if(isatty(f) == 0)
		return(NULL);
	if(fstat(f, &fsb) < 0)
		return(NULL);
	if((fsb.st_mode & S_IFMT) != S_IFCHR)
		return(NULL);

	/*
	 * generate a tty name
	 * if this isn't the inode in use, search /dev the old way
	 */
	rbufptr = strcpy(rbuf, dev_to_ttyname(fsb.st_rdev));
	if (stat(rbufptr, &tsb) == 0
	&& tsb.st_rdev == fsb.st_rdev
	&& (tsb.st_mode&S_IFMT) == S_IFCHR
	&& tsb.st_ino == fsb.st_ino) {
		return(rbufptr);
	}

	pass1 = 1;
	do {
		if ((dir = opendir(dev)) == NULL)
			return(NULL);
		for (db = readdir(dir); db != NULL; db = readdir(dir)) {
			if(db->d_ino == 0)
				continue;
			if(pass1 && db->d_ino != fsb.st_ino)
				continue;
			(void) strcpy(rbuf, dev);
			(void) strcat(rbuf, db->d_name);
			if(stat(rbuf, &tsb) < 0)
				continue;
			if(tsb.st_rdev == fsb.st_rdev &&
				(tsb.st_mode&S_IFMT) == S_IFCHR &&
				(!pass1 || tsb.st_ino == fsb.st_ino)) {
				closedir(dir);
				return(rbuf);
			}
		}
		closedir(dir);
	} while(pass1--);
	return(NULL);
}
