/*
 *
 * anno.c
 *
 * Delete announcements older than ANNO_KEEP_DAYS
 * Ken Stevens, 1995
 */

#include "misc.h"
#include "tel.h"
#include <stdio.h>
#include <fcntl.h>
#include <sys/file.h>

delete_old_announcements()
{
	time_t	now;
	time_t	old;
	struct	telstr tgm;
	FILE   *oldfp;
	int     tmpfd;
	s_char	tmp_filename[1024];
	int	writeit;
	s_char	message[MAXTELSIZE];
	int	deleted = 0;
	int	saved = 0;
	int	length;
	int     nbytes;
	int	first = 1;

	time(&now);
	old = now - days(ANNO_KEEP_DAYS);
	logerror("Deleting annos older than %s", ctime(&old));

	if ((oldfp = fopen(annfil, "r+")) == 0) {
		logerror("can't read telegram file %s", annfil);
		return;
	}
	sprintf(tmp_filename, "%s.tmp", annfil);
	while (fread((s_char *) &tgm, sizeof(tgm), 1, oldfp) == 1) {
		writeit = 1;
		if (tgm.tel_length < 0) {
			logerror("bad telegram file header (length)");
			return;
		}
		if (tgm.tel_type < 0 || tgm.tel_type > TEL_LAST) {
			logerror("bad telegram file header (type)");
			writeit = 0;
		}
		if (first) {
			first = 0;
			if (tgm.tel_date >= old) {
				fclose(oldfp);
				return;
			}
			if ((tmpfd = open(tmp_filename, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0) {
				logerror("can't write telegram file %s", tmp_filename);
				return;
			}
		}
	
		if (tgm.tel_date < old) {
			writeit = 0;
		}

		if (writeit) {
			if (write(tmpfd, &tgm, sizeof(tgm)) < sizeof(tgm)) {
				logerror("error writing to ann.tmp");
				return;
			}
			++saved;
		} else {
			++deleted;
		}
		length = tgm.tel_length;
		while (length > 0) {
			nbytes = length;
			if (nbytes > sizeof(message))
				nbytes = sizeof(message);
			(void) fread(message, sizeof(s_char), nbytes, oldfp);
			if (writeit) {
				if (write(tmpfd, message, nbytes) < nbytes) {
					logerror("Error writing to ann.tmp");
					return;
				}					
			}
			length -= nbytes;
		}
	}
	logerror("%d announcements deleted; %d announcements saved",
		 deleted, saved);
	fclose(oldfp);
	close(tmpfd);
	unlink(annfil);
	rename(tmp_filename, annfil);
}
