/*
** watrots.c - routines to read in a decipher dbase file.
**           - For the finger distribution.
**
** Written by Keith Gabryelski
** Released into public domain September 1, 1988.
** Please keep this header.
**
** Some basic routines used to handle data base management.
*/

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <a.out.h>
#include <fcntl.h>
#include "defs.h"
#include "ttyloc.h"
#include "dbase.h"

extern char *mymalloc(), *myrealloc();

#define GET_NEXT_LINE()	{cp = bp; if (bp != NULL) 			\
			{while (*bp != '\n' && bp < bufferend)  *bp++;	\
			     if (bp >= bufferend) bp = NULL;		\
			     else *bp++ = '\0';}}

void
get_dbase_info(f)
struct finger *f;
{
    char *bp, *cp, *dp, *buffer = NULL, *bufferend;
    char whoisname[sizeof(WHOIS_DBASE_DIR) + sizeof('/') + sizeof(f->uname)];
    int fd;
    struct stat stbuf;

    strcpy(whoisname, WHOIS_DBASE_DIR);
    strcat(whoisname, "/");
    strcat(whoisname, f->uname);

    f->work_addr = f->home_addr = f->work_phone = f->birthday =
	f->home_phone = f->project = f->supervisor =
	    f->remark = f->nickname = "";

    if ((fd = open(whoisname, O_RDONLY)) != -1 && fstat(fd, &stbuf) != -1)
    {
	f->valid_whois = TRUE;
	buffer = myrealloc(buffer, stbuf.st_size + 1);

	bufferend = buffer + stbuf.st_size;
	bp = buffer;
	dp = NULL;
	if (read(fd, buffer, stbuf.st_size) > 0)
	{
	    GET_NEXT_LINE();

	    if (cp != NULL)
	    {
		f->nickname = mymalloc(strlen(cp) + 1);
		strcpy(f->nickname, cp);
	    }

	    GET_NEXT_LINE();

	    if (cp != NULL)
	    {
		f->work_addr = mymalloc(strlen(cp) + 1);
		strcpy(f->work_addr, cp);
	    }

	    GET_NEXT_LINE();

	    if (cp != NULL)
	    {
		f->work_phone = mymalloc(strlen(cp) + 1);
		strcpy(f->work_phone, cp);
	    }

	    GET_NEXT_LINE();

	    if (cp != NULL)
	    {
		f->home_addr = mymalloc(strlen(cp) + 1);
		strcpy(f->home_addr, cp);
	    }

	    GET_NEXT_LINE();

	    if (cp != NULL)
	    {
		f->home_phone = mymalloc(strlen(cp) + 1);
		strcpy(f->home_phone, cp);
	    }

	    GET_NEXT_LINE();

	    if (cp != NULL)
	    {
		f->birthday = mymalloc(strlen(cp) + 1);
		strcpy(f->birthday, cp);
	    }

	    GET_NEXT_LINE();

	    if (cp != NULL)
	    {
		f->project = mymalloc(strlen(cp) + 1);
		strcpy(f->project, cp);
	    }

	    GET_NEXT_LINE();

	    if (cp != NULL)
	    {
		f->supervisor = mymalloc(strlen(cp) + 1);
		strcpy(f->supervisor, cp);
	    }

	    cp = bp; /* Get remark. */

	    if (bp != NULL)
	    {
		while (bp < bufferend)
		    bp++;

		*bp++ = '\0';

		f->remark = mymalloc(bp - cp);
		strcpy(f->remark, cp);
	    }
	}

	close(fd);
    }
    else
	f->valid_whois = FALSE;
}
