/*
 * newsrc file handling
 */

#include "defs.h"

static char nrcname[]	 = NEWSRC;

static char *rcname;		/* full pathname of .newsrc */
newsrc *rc;			/* internal .newsrc */
char *rcgrps;			/* subscription from .newsrc */
static newsrc *lastrc;		/* last newsrc struct in list */
static int rclineno;		/* current lineno in .newsrc */
static bool sortrc;		/* if we should sort on output */

static newsrc *findnewsrc();

readnewsrc()
{
	register FILE *f;
	static char option[] = "options";
	char word[BUFSIZ], rest[BUFSIZ];
	extern char *getenv();

	if ((rcname = getenv("HOME")) == NULL)
		error("No $HOME in environment.");
	rcname = newstr3(rcname, "/", nrcname);
	if ((f = fopen(rcname, "r")) == NULL)
		return;

	rclineno = 0;
	while (getline(f, word, rest))
		if (CMP(word, option) == 0)
			dooptions(rest);
		else
			dorcline(word, rest);
	(void) fclose(f);
}

/*
 * Read a line from f, put first word into w and the rest into r.
 * Discard trailing newline instead of storing it.
 * This is a poor design, as w & r are unchecked for overrun.
 */
static
getline(f, w, r)
register FILE *f;
char *w, *r;
{
	register int c;
	register char *s;

	rclineno++;
	s = w;
	while ((c = getc(f)) != EOF && c != ' ' && c != '\t')
		*s++ = c;			/* stash first word */
	*s = '\0';

	if (c != EOF) {
		s = r;
		while ((c = getc(f)) != EOF && c != '\n')
			*s++ = c;		/* stash the rest */
		*s = '\0';
	}

	if (c != '\n' && c != EOF)
		error("Bad format: %s line %d: %s", rcname, rclineno, w);

	return c != EOF;
}

/*
 * Parse s into words and simulate command line arguments with them.
 */
static
dooptions(s)
char *s;
{
	register char *cp;
	register int argc;
	register char **argv;

	cp = s;
	while (isspace(*cp))
		cp++;
	if (!*cp)
		return;

	argc = 1;
	argv = (char **) myalloc(sizeof(char *));
	argv[argc - 1] = cp;
	while (*cp && (cp = strpbrk(cp, " \t")) != NULL) {
		while (*cp == ' ' || *cp == '\t')
			*cp++ = '\0';
		if (*cp) {
			argc++;
			argv = (char **) myrealloc((char *) argv,
				argc * (int)sizeof(char *));
			argv[argc - 1] = cp;
		}
	}
	if (options(argc, argv, false))
		error("Bad options: %s line %d: %s", rcname, rclineno, s);
	free((char *) argv);
}

/*
 * Parse w & r together as a .newsrc newsgroup line.
 */
static
dorcline(w, r)
char *w, *r;
{
	register char lastw;
	register int len;
	register newsrc	*np;

	len = strlen(w);
	lastw = w[len - 1];			/* save presumed colon or bang */
	w[len - 1] = '\0';			/* nuke presumed colon */
	while (*r == ' ' || *r == '\t')
		r++;				/* skip extra whitespace *
