/*
 * Copyright 1993, 1994 by Ulrich Khn. All rights reserved.
 *
 * THIS PROGRAM COMES WITH ABSOLUTELY NO WARRANTY, NOT
 * EVEN THE IMPLIED WARRANTIES OF MERCHANTIBILITY OR
 * FITNESS FOR A PARTICULAR PURPOSE. USE AT YOUR OWN
 * RISK.
 */

/*
 * File : auth.c
 *        read and eval the epxorts file
 */

#include <stdio.h>
#include <string.h>
#include <memory.h>
#include <types.h>
#include <stat.h>
#include "../xfs/nfs.h"
#include "util.h"
#include "exportent.h"
#include "auth.h"




exportlist *exports = NULL;
client_info *clients = NULL, *unknown_clients = NULL;


void free_old_lists()
{
	exportlist *ex;
	client_info *cl;

	ex = exports;
	while (ex)
	{
		exports = ex->ex_next;
		free(ex->ex_filesys);
		free(ex);
		ex = exports;
	}

	cl = clients;
	while (cl)
	{
		clients = cl->next;
		free(cl);
		cl = clients;
	}

	cl = unknown_clients;
	while (cl)
	{
		unknown_clients = cl->next;
		free(cl);
		cl = unknown_clients;
	}

	exports = NULL;
	clients = NULL;
	unknown_clients = NULL;
}



int
auth_init()
{
	struct exportent *xent;
	FILE *fp;
	long r;
	struct stat stats;
	char buf[MAXPATHLEN+1];
	char *mountpoint, *p;
	exportlist *exprt;
	groups *gr;
	client_info *clnt;

	if (exports || clients || unknown_clients)
		free_old_lists();

	fp = setexportent();
	if (!fp)
	{
		return -1;
	}

	while ((xent = getexportent(fp)) != NULL)
	{
		/* convert the path into an internal native format */
		if (path2abs(xent->xent_dirname, buf) != 0)
			break;          /* some serious error occured */

		/* first check if the entry represents a valid thing
		 * in the file system; follow symbolic links.
		 */
		r = stat(buf, &stats);
		if (r != 0)
		{
			/* Invalid entry in the export file found, ignore it */
			continue;
		}
	
		/* prepare the mount entry */
		mountpoint = malloc(strlen(buf)+1);
		if (!mountpoint)
			break;
		strcpy(mountpoint, buf);

		exprt = malloc(sizeof(exportlist));
		if (!exprt)
		{
			free(mountpoint);
			break;
		}
		exprt->ex_groups = NULL;
		exprt->ex_filesys = mountpoint;
		exprt->ex_next = exports;
		exports = exprt;
#if 0
		if ((p = getexportopt(exprt, ACCESS_OPT))!= NULL)
		{
			char *s;
			int n;

			s = p;
			n = 0;
			while (*s && (*s != ',') && !iswhite(*s))
			{
				n++;
				s++;
			}
			clnt = malloc(sizeof(client_info));
			if (!clnt)
				break;
			clnt->name = malloc(n+1);
			if (!clnt->name)
			{
				free(clnt);
				break;
			}
			strncpy(clnt->name, p);
			clnt->name[n] = '\0';
			clnt->mountpoint = mountpoint;
			gr = malloc(sizeof(groups));
			if (!gr)
			{
				free(clnt->name);
				free(clnt);
				break;
			}
			gr_name = clnt->name;
			gr->gr_next = exprt->ex_groups;
			exprt->ex_groups = gr;
		}

#endif

	}

	endexportent(fp);

	if (exports)
		return 0;
	else
		return -1;
}
