/*
 *   Copyright (C) 1988-2006 Lucent Technologies Inc. and others.
 *   All Rights Reserved.
 */

/*
 *	logdir()
 *
 *	This routine does not use the getpwent(3) library routine
 *	because the latter uses the stdio package.  The allocation of
 *	storage in this package destroys the integrity of the shell's
 *	storage allocation.
 */

#include <fcntl.h>	/* O_RDONLY */
#if defined( __STDC__ ) || defined( __BORLANDC__ )
#include <stdlib.h>

#ifdef __BORLANDC__
#include <io.h>
#include <string.h>
#endif

char	*logdir(char *name);
static char	*passwdfield(char *p);
#elif cygwin || darwin
off_t	lseek();
#else
long	lseek();
#endif

#define	BUFSIZ	160

static char line[BUFSIZ+1];

static char *
passwdfield(p)
register char *p;
{
	while (*p && *p != ':')
		++p;
	if (*p) *p++ = 0;
	return(p);
}

char *
logdir(name)
char *name;
{
	register char	*p;
	register int	i, j;
	int	pwf;
	
	/* attempt to open the password file */
	if ((pwf = open("/etc/passwd", O_RDONLY)) == -1)
		return(0);
		
	/* find the matching password entry */
	do {
		/* get the next line in the password file */
		i = read(pwf, line, BUFSIZ);
		for (j = 0; j < i; j++)
			if (line[j] == '\n')
				break;
		/* return a null pointer if the whole file has been read */
		if (j >= i)
			return(0);
		line[++j] = 0;			/* terminate the line */
#if darwin
		(void) lseek(pwf, (off_t) (j - i), 1);	/* point at the next line */
#else
		(void) lseek(pwf, (long) (j - i), 1);	/* point at the next line */
#endif
		p = passwdfield(line);		/* get the logname */
	} while (*name != *line ||	/* fast pretest */
	    strcmp(name, line) != 0);
	(void) close(pwf);
	
	/* skip the intervening fields */
	p = passwdfield(p);
	p = passwdfield(p);
	p = passwdfield(p);
	p = passwdfield(p);
	
	/* return the login directory */
	(void) passwdfield(p);
	return(p);
}
