/*
 * W-NEWS       A simple NEWS processing package.
 *              WNsort is used to re-sort the "active" file after some major
 *		spool directory corruption.  Basiclly, it walks down the en-
 *		tire spool tree, scanning each directory for valid articles,
 *		and maintaining a count of how many articles each directory
 *		has.  This info is printed on standard output, which can be
 *		redirected into a new "active" file.
 *
 * Usage:       wnsort [ group ... ] [ > active_file]
 *
 * Version:     @(#)wnsort.c	4.40	11/24/93
 *
 * Author:      Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
 *		Copyright 1988-1993 MicroWalt Corporation
 *
 *		This program is free software; you can redistribute it and/or
 *		modify it under the terms of the GNU General Public License
 *		as published by the Free Software Foundation; either version
 *		2 of the License, or (at your option) any later version.
 */
#include "wnews.h"


char *Release = VERSION;
char *Version = "@(#) wnsort 4.40 (11/24/93)";


void check_one(name)
char *name;
{
  char path[1024];
  struct dirent *de;
  DIR *dp;
  char *sp, *nix;
  unsigned long val, ex, hi;
  int flag = 0;

  sprintf(path, "%s/%s", SPOOLDIR, name);
  while ((sp = strchr(path, '.')) != NULL) *sp = '/';

  if ((dp = opendir(path)) == NULL) {
	fprintf(stderr, "%s: %s\n", path, strerror(errno));
	return;
  }

  hi = 0;
  ex = 32000000;
  (void)readdir(dp);		/* . */
  (void)readdir(dp);		/* .. */
  while ((de = readdir(dp)) != NULL) {
	if (!isdigit(*de->d_name)) continue;

	val = strtoul(de->d_name, &nix, 0);
	if (val < ex) ex = val;
	if (val > hi) hi = val;
	flag = 1;
  }
  if (flag == 0) {
	ex = 0;
	hi = 0;
  }
  printf("%s %05lu %05lu", name, hi, ex);
  (void) closedir(dp);
}


void check_all()
{
  char active[1024];
  char buff[1024];
  char *sp, *nix;
  unsigned long high;
  unsigned long expired;
  FILE *fp;

  sprintf(active, "%s/%s", CONFDIR, ACTIVE);
  if ((fp = fopen(active, "r")) == NULL) {
	perror(active);
	exit(ERROR);
  }

  while (fgets(buff, 1024, fp) != NULL) {
	buff[strlen(buff) - 1] = '\0';

	if ((sp = strchr(buff, ' ')) == NULL) {
		fprintf(stderr, "active format error: \"%s\"\n", buff);
		continue;
	}
	*sp++ = '\0';
	high = strtoul(sp, &nix, 0);
	if ((sp = strchr(sp, ' ')) == NULL) {
		fprintf(stderr, "active format error: \"%s\"\n", sp);
		continue;
	}
	*sp++ = '\0';
	expired = strtoul(sp, &nix, 0);
	if ((sp = strchr(sp, ' ')) == NULL) {
		fprintf(stderr, "active format error: \"%s\"\n", sp);
		continue;
	}
	*sp++ = '\0';

	check_one(buff);
	printf(" %s\n", sp);
  }
}


void main(argc, argv)
int argc;
char *argv[];
{
  if (argc > 1) {
	while(--argc > 0) {
		check_one(*++argv);
		printf("\n");
	}
  } else {
	check_all();
  }

  exit(OK);
}
