
/*
 *  GETPWNAM.C
 *
 *  $Header: Beta:src/uucp/src/lib/RCS/getpwnam.c,v 1.1 90/02/02 12:08:26 dillon Exp Locker: dillon $
 *
 *  (C) Copyright 1989-1990 by Matthew Dillon,  All Rights Reserved.
 *
 *  (UUCP source support)
 */

#include <stdio.h>
#include <stdlib.h>
#include <pwd.h>
#include "config.h"

Prototype struct passwd *getpwnam(const char *);

Local char *Breakout(char **);

char *PasswdFile;

struct passwd *
getpwnam(name)
const char *name;
{
    FILE *fi;
    char *buf = malloc(256);
    static char User[32];
    static char Passwd[32];
    static char Dir[128];
    static char Shell[256];
    static struct passwd Pas = { User, Passwd, 0, 0, 0, "", "", Dir, Shell };

    if (PasswdFile)
	fi = fopen(PasswdFile, "r");
    else
	fi = fopen(MakeConfigPath(UULIB, "Passwd"), "r");

    if (fi == NULL) {
	free(buf);
	return(NULL);
    }

    while (fgets(buf, 256, fi)) {
	char *ptr = buf;
	char *arg;

	arg = Breakout(&ptr);
	if (strcmp(name, arg) != 0)
	    continue;
	strcpy(Pas.pw_name, arg);
	strcpy(Pas.pw_passwd, Breakout(&ptr));
	Pas.pw_uid = atoi(Breakout(&ptr));
	Pas.pw_gid = atoi(Breakout(&ptr));
	Breakout(&ptr);     /*  finger info */
	strcpy(Pas.pw_dir, Breakout(&ptr));
	strcpy(Pas.pw_shell, Breakout(&ptr));

	{
	    short i = strlen(Pas.pw_dir) - 1;
	    if (i >= 0 && Pas.pw_dir[i] != ':' && Pas.pw_dir[i] != '/') {
		Pas.pw_dir[i++] = '/';
		Pas.pw_dir[i] = 0;
	    }
	}

	{
	    char *str;

	    Pas.pw_shell_arg0 = Pas.pw_shell;
	    for (str = Pas.pw_shell; *str && *str != ' ' && *str != 9; ++str);
	    if (*str) {
		*str = 0;
		++str;
		while (*str == ' ' || *str == 9)
		    ++str;
		Pas.pw_shell_argn = str;
	    } else {
		Pas.pw_shell_argn = str;
	    }
	}


	fclose(fi);
	free(buf);
	return(&Pas);
    }
    free(buf);
    fclose(fi);
    return(NULL);
}

static
char *
Breakout(pptr)
char **pptr;
{
    char *base;
    char *ptr;

    base = *pptr;
    if (base == NULL)
	return("");
    for (ptr = base; *ptr && *ptr != '\n' && *ptr != ','; ++ptr);
    if (*ptr == ',') {
	*pptr = ptr + 1;
	*ptr = 0;
    } else {
	*pptr = NULL;
	*ptr = 0;
    }
    return(base);
}

