/*
 * 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 : exportent.c
 *        access files containing file system information
 *
 */


#include <stdio.h>
#include <support.h>
#include <ctype.h>
#include <file.h>
#include <errno.h>
#include "exportent.h"



#define MAX_LINE_LEN 80


static struct exportent the_xent;
static char the_xbuf[MAX_LINE_LEN+2];


FILE *
setexportent()
{
	FILE *fp;
	int i;

	/* open the file */
	fp = fopen(TABFILE, "r+");
	if (!fp)
		return NULL;

	/* set up some static buffers etc. */
	the_xent.xent_dirname = NULL;
	the_xent.xent_options = NULL;
	for (i = 0;  i < MAX_LINE_LEN+2;  i++)
		the_xbuf[i] = '\0';

	return fp;
}


void
endexportent(FILE *fp)
{
	fclose(fp);
}



struct exportent *
getexportent(FILE *fp)
{
	char *p;

read_again:
	p = fgets(the_xbuf, MAX_LINE_LEN, fp);
	if (p == NULL)
		return NULL;

	/* strip off tailing line separator */
	p = the_xbuf;
	while (*p && (*p != '\r') && (*p != '\n'))
		p++;
	*p = '\0';

	/* check for comments */
	if (the_xbuf[0] == '#')   /* if that line is a comment, do it again */
	{
		goto read_again;
	}

	/* now scan the line and set the exportent struct accordingly */
	p = the_xbuf;
	while (*p && iswhite(*p))   /* skip leading white spaces */
		p++;
	the_xent.xent_dirname = p;
	while (*p && !iswhite(*p))
		p++;
	if (*p)
		*p++ = '\0';

	while (*p && iswhite(*p))
		p++;
	the_xent.xent_options = p;
	while (*p && !iswhite(*p))
		p++;
	if (*p)
		*p++ = '\0';

	return &the_xent;
}


int
addexportent(FILE *fp, char *dirname, char *options)
{
	char line[MAX_LINE_LEN+3];
	char *p, *s;
	long n, r;

	/* wait for a lock on that file */
	while ((r = flock(fileno(fp), LOCK_EX)) == ELOCKED)    ;

	if (r != 0)
		return -1;

	fseek(fp, 0, SEEK_END);   /* go to end of file */
	n = 0;
	p = line;
	if (dirname)
	{
		for (s = dirname;  (n < MAX_LINE_LEN-1) && *s;  n++)
			*p++ = *s++;
		*p++ = ' ';
		n++;
	}

	if (options)
	{
		for (s = options;  (n < MAX_LINE_LEN-1) && *s;  n++)
			*p++ = *s++;
		*p++ = ' ';
		n++;
	}
	*p++ = '\r';
	*p++ = '\n';
	*p = '\0';

	r = fwrite(line, 1, n+2, fp);

	flock(fileno(fp), LOCK_UN);   /* unlock file */

	if (r == n)
		return 0;
	else
		return -1;
}


int
remexportent(FILE *fp, char *dirname)
{
	return -1;
}


char *
getexportopt(struct exportent *xent, char *opt)
{
	return NULL;
}
