
/*
 *  TRIMNEWS.C
 *
 *  TRIMNEWS
 *
 *  This program scans UULIB:NewsGroups then chdir's into each news group's
 *  directory.	The second field specifies the number of days old any numerical
 *  file (ifilename beginning with 0-9) is allowed to be before it is deleted.
 *
 *  If the second field does not exist for a given line in the NewsGroups file,
 *  7 days is automatically assumed.  The number of days is referenced from
 *  when the file was created, NOT the Date: field in the article.
 *
 *  The program is meant to be run daily from a DCron entry to clear out old
 *  news.
 */

#include <stdio.h>
#include <stdlib.h>
#include "config.h"
#include "version.h"
#include <libraries/dos.h>

typedef struct FileInfoBlock	FIB;

IDENT(".01");

static char TmpBuf[256];

void ScanDirectoryDeleteFiles();

int
brk()
{
    return(0);
}

main(ac, av)
char *av[];
{
    FILE *fi;
    char *path;
    char newsgrp[64];
    int days;

    onbreak(brk);
    fi = openlib("NewsGroups");
    if (fi == NULL) {
	puts("Unable to open NewsGroups file");
	exit(1);
    }
    while (fgets(TmpBuf, sizeof(TmpBuf), fi)) {
	switch (sscanf(TmpBuf, "%s %d", newsgrp, &days)) {
	case 1:
	    days = 7;
	case 2:
	    path = MakeConfigPath(UUNEWS, newsgrp);
	    if (days)
		ScanDirectoryDeleteFiles(path, days);
	}
    }
    fclose(fi);
    return(0);
}

void
ScanDirectoryDeleteFiles(path, days)
char *path;
int days;
{
    BPTR lock;
    BPTR oldlock;
    FIB *fib;
    long ds[3];
    long tnow;

    DateStamp(ds);
    tnow = dstot(ds) - days * 1440*60;

    if (lock = Lock(path, ACCESS_READ)) {
	oldlock = CurrentDir(lock);
	if (fib = malloc(sizeof(FIB))) {
	    if (Examine(lock, fib)) {
		while (ExNext(lock, fib)) {
		    if (isdigit((unsigned char)fib->fib_FileName[0])) {
			if (tnow > dstot(&fib->fib_Date))
			    DeleteFile(fib->fib_FileName);
		    }
		}
	    }
	    free(fib);
	}
	UnLock(CurrentDir(oldlock));
    }
}

long
dstot(date)
long *date;	/*  days, mins, ticks	*/
{
    return(date[0] * 1440 * 60 + date[1] * 60 + date[2] / 50);
}

