/*--------------------------------------------------------------------- */
/* updact.c								*/
/*	Reads in "news:active" and for each news group finds the last   */
/*	article. Writes out the updated active file			*/
/*									*/
/* History:								*/
/*	2 Nov 1990	v1.0    Unreleased 				*/
/*     23 Nov 1990	v2.0	Unreleased				*/
/*     17 Feb 1991	v2.1	          				*/
/*									*/
/* TODO:								*/
/*									*/
/*	Make the logic quicker 						*/
/*									*/
/* Author:								*/
/*	Michael Taylor 							*/
/*	Canberra, AUSTRALIA						*/
/*--------------------------------------------------------------------- */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#ifdef DICE
#include "stat.h"
#else
#include <sys/stat.h>
#endif
#ifdef DICE
typedef unsigned char uchar;
#endif

static uchar	line[257];
#define MAXGRPS 100
static uchar    act_lines[MAXGRPS][257];

#define MAXSKIP 1000

main (argc, argv)
int	argc;
uchar	*argv[];
{
	FILE	*active;
	uchar	*p, fname[80], newsdir[256], artfile[80], *q;
	long    article, art2;
	int     i, j, limit, fin, found;
	struct stat	statbuf;
	
	active = fopen ("news:active", "rt");
	if (active == NULL) {
		fprintf (stderr, "active file not found\n");
		exit (EXIT_FAILURE);
	}

	i = 0;
	while (fgets (line, 80, active) != NULL) {
		if (sscanf (line, "%s %s", newsdir, fname) != 2)
			break; /* syntax error on line */

		for (q = newsdir; *q != '\0'; ++q)
			if (*q == '.')
				*q = '/';

		found = 1;
		for (article = atol(fname), limit = MAXSKIP;; ++article) {
			strcpy (artfile, "news:");
			strcat (artfile, newsdir);
			strcat (artfile, "/");
			strcat (artfile, ltoa (article, fname, 10));

			fin = stat (artfile, &statbuf);
			if (fin == -1) {
				for (art2 = article + 1, j = 0;;
				     ++art2, ++j) {
					strcpy (artfile, "news:");
					strcat (artfile, newsdir);
					strcat (artfile, "/");
					strcat (artfile,
						ltoa (art2, fname, 10));

					fin = stat (artfile, &statbuf);
					if (fin != -1) {
						article = art2;
						break;
					} else
						if (j >= limit)
							break;
				}
				if (art2 != article)
					break;

				found = 0;
			} else {
				limit = 25; /* reset limit for missing art's */
				found = 0;
			}
		}
		sscanf (line, "%s", newsdir);
		strcpy (act_lines[i], newsdir);
		strcat (act_lines[i], " ");
		strcat (act_lines[i], ltoa (article-1+found, fname, 10));
		++i;
		if (i >= MAXGRPS) {
			fprintf (stderr,
				"Maximum number of groups read: %d \n",
				MAXGRPS);
			break;
		}
	}

	act_lines[i][0] = ' ';
	fclose (active);
	active = fopen ("news:active", "wt");
	if (active == NULL) {
		fprintf (stderr, "could not open active file\n");
		exit (EXIT_FAILURE);
	}
	for (i = 0; act_lines[i][0] != ' '; ++i)
		fprintf (active, "%s\n", act_lines[i]);
	fclose (active);
	exit (EXIT_SUCCESS);
}
