/*
 * YP: a class that does nothing but read and write yp.conf
 *
 * Copyright (c) 1997 David L Parsons 
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms are permitted
 * provided that the above copyright notice and this paragraph are
 * duplicated in all such forms and that any documentation,
 * advertising materials, and other materials related to such
 * distribution and use acknowledge that the software was developed
 * by David L Parsons (orc@pell.chi.il.us).  My name may not be used
 * to endorse or promote products derived from this software without
 * specific prior written permission.  THIS SOFTWARE IS PROVIDED
 * ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
 * WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE.
 */
static const char rcsid[] = "$Id: s.YP.cc 1.6 98/08/28 05:19:47-00:00 orc $";

#include "YP.H"

extern "C" {
#include <ctype.h>
#include <unistd.h>
#include <string.h>
}

#include "util.H"

#ifndef _PATH_YPCONF
#define _PATH_YPCONF	"/etc/yp.conf"
#endif

/*
 * YP::YP initial creation and load
 */
YP::YP():KA()
{
    _magic = 0;
    Refresh();
} /* YP::YP */

/*
 * YP::Refresh() loads /etc/yp.conf
 */
int
YP::Refresh()
{
    FILE *f;

    Zero();

    if ((f = fopen(_PATH_YPCONF, "r")) != (FILE*)0) {
	read(f);
	fclose(f);
    }
    changed(0);
    return count();
} /* YP::Refresh() */


/*
 * YP::read() actually reads a yp.conf file
 */
int
YP::read(FILE *from)
{
    char bfr[200];
    char *p;

    Zero();

    _magic = 0;
    while (fgets(bfr, sizeof bfr, from)) {
	if (strncasecmp("magic", bfr, 5) == 0 && isspace(bfr[5])) {
	    _magic = (strstr(bfr, "cookie") != 0);
	    continue;
	}
	if (strncasecmp("ypserver", bfr, 8) != 0 || !isspace(bfr[8]))
	    continue;

	for (p = bfr+8; *p && isspace(*p); ++p)
	    ;
	strtok(p, "\t \n");
	if (*p)
	    *this += p;
    }
    return count();
} /* YP::read */


/*
 * YP::commit() writes a changed yp.conf back to disk (or deletes it if
 * there are no yp servers)
 */
int
YP::commit()
{
    FILE *f;

    if (backup(_PATH_YPCONF) != 0)
	return EOF;
    if ((f = fopen(_PATH_YPCONF, "w")) != (FILE*)0) {
	make_header(f, 0);
	if (count() != 0)
	    print(f);
	else
	    fprintf(f, "# this file intentionally left blank\n");
	fclose(f);
    }
    else
	return EOF;

    return 0;
} /* YP::commit */
