#include "args.h"
#include "config.h"
/*
 * Copyright (c) 1986, 2014 by The Trustees of Columbia University in
 * the City of New York.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *  + Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 *  + Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 *  + Neither the name of Columbia University nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 */


#ifndef lint
static const char *rcsid = "$Header: /usr/local/src/mm/mm-0.94/mm/RCS/whoami.c,v 1.1 2005/05/28 22:27:54 beebe Exp $";
#endif

/*
 * whoami - return the user's login name
 *
 * In order to handle the situation where several login names map to the
 * same uid, the USER and LOGNAME environment variables, and the
 * /etc/utmp file are consulted for a name with a uid matching that
 * returned by getuid().  If that fails, the first entry in the passwd
 * database with a matching uid is returned.
 *
 * If no name matching the current uid is found, NULL is returned.
 */

#include "args.h"
#include "config.h"
#include "osfiles.h"
#include "compat.h"
#include <pwd.h>

static const char *envariables[] = { "USER", "LOGNAME" };

char *
#if HAVE_STDC
whoami (void)
#else /* K&R style */
whoami (VOID)
#endif /* HAVE_STDC */
{
    int i;
    char *cp;
    struct passwd *pw;
    static int realuid = -1;		/* user's real uid */
    static char realname[64];		/* user's name */

    if (realuid != -1)
	return realname;

    realuid = getuid ();	       /* get our uid */

    /*
     * Check the conventional environment variables...
     */
    for (i = 0; i < sizeof envariables / sizeof envariables[0]; i++)
	if ((cp = getenv (envariables[i]), cp))
	    if ((pw = getpwnam (cp), pw))
		if (pw->pw_uid == realuid) {
		    strcpy (realname, cp);
		    return realname;
		}

    /*
     * See if there is an entry in the utmp file...
     */
    if ((cp = getlogin (), cp))
	if ((pw = getpwnam (cp), pw))
	    if (pw->pw_uid == realuid) {
		strcpy (realname, cp);
		return (realname);
	    }

    /*
     * Finally, look for the first maching entry in the passwd file.
     */
    if ((pw = getpwuid (realuid), pw)) {
	strcpy (realname, pw->pw_name);
	return realname;
    }

    realuid = -1;
    return NULL;
}
