/*----------------------------------------------------------------------
      Pull the name out of the gcos field if we have that sort of /etc/passwd

   Args: gcos_field --  The long name or GCOS field to be parsed
         logname    --  Replaces occurances of & with logname string

 Result: returns pointer to buffer with name
  ----*/
static char *
gcos_name(gcos_field, logname)
    char *logname, *gcos_field;
{
    static char fullname[MAX_FULLNAME+1];
    register char *fncp, *gcoscp, *lncp, *end;

    /* full name is all chars up to first ',' (or whole gcos, if no ',') */
    /* replace any & with logname in upper case */

    for(fncp = fullname, gcoscp= gcos_field, end = fullname + MAX_FULLNAME - 1;
        (*gcoscp != ',' && *gcoscp != '\0' && fncp != end);
	gcoscp++) {

	if(*gcoscp == '&') {
	    for(lncp = logname; *lncp; fncp++, lncp++)
		*fncp = toupper((unsigned char)(*lncp));
	} else {
	    *fncp++ = *gcoscp;
	}
    }
    
    *fncp = '\0';
    return(fullname);
}


/*----------------------------------------------------------------------
      Fill in homedir, login, and fullname for the logged in user.
      These are all pointers to static storage so need to be copied
      in the caller.

 Args: ui    -- struct pointer to pass back answers

 Result: fills in the fields
  ----*/
void
get_user_info(ui)
    struct user_info *ui;
{
    struct passwd *unix_pwd;

    unix_pwd = getpwuid(getuid());
    if(unix_pwd == NULL) {
      ui->homedir = cpystr("");
      ui->login = cpystr("");
      ui->fullname = cpystr("");
    }else {
      ui->homedir = cpystr(unix_pwd->pw_dir);
      ui->login = cpystr(unix_pwd->pw_name);
      ui->fullname = cpystr(gcos_name(unix_pwd->pw_gecos, unix_pwd->pw_name));
    }
}


/*----------------------------------------------------------------------
      Look up a userid on the local system and return rfc822 address

 Args: name  -- possible login name on local system

 Result: returns NULL or pointer to alloc'd string rfc822 address.
  ----*/
char *
local_name_lookup(name)
    char *name;
{
    struct passwd *pw = getpwnam(name);

    if(pw == NULL){
	char *p;

	for(p = name; *p; p++)
	  if(isupper((unsigned char)*p))
	    break;

	/* try changing it to all lower case */
	if(p && *p){
	    char *lcase;

	    lcase = cpystr(name);
	    for(p = lcase; *p; p++)
	      if(isupper((unsigned char)*p))
		*p = tolower((unsigned char)*p);

	    pw = getpwnam(lcase);

	    if(pw)
	      strcpy(name, lcase);

	    fs_give((void **)&lcase);
	}
    }

    if(pw == NULL)
      return((char *)NULL);

    return(cpystr(gcos_name(pw->pw_gecos, name)));
}


