/*
 * histinfo - print history file lines for articles named on stdin
 */

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>		/* for modified time (date received) */
#include "config.h"

#define MAXLINE 1024
#define STRLEN(s) (sizeof(s) - 1)	/* s must be a char array */

char *progname;
int debug;

FILE *efopen();

char *spdir;
int spdirlen;

/*
 * main - parse arguments and handle options
 */
main(argc, argv)
int argc;
char *argv[];
{
	int c;
	int errflg = 0;
	FILE *in;
	char inname[MAXLINE];
	extern int optind;
	extern char *optarg;

	progname = argv[0];
	while ((c = getopt(argc, argv, "d")) != EOF)
		switch (c) {
		case 'd':
			++debug;
			break;
		default:
			errflg++;
			break;
		}
	if (optind < argc || errflg) {
		(void) fprintf(stderr, "usage: %s [-d]\n", progname);
		exit(2);
	}

	spdir = artfile((char *)NULL);
	spdirlen = strlen(spdir);
	
	while (fgets(inname, sizeof(inname), stdin) != NULL) {
		inname[strlen(inname)-1] = '\0';	/* kill newline */
		in = efopen(inname, "r");
		process(in, inname);
		(void) fclose(in);
	}
	exit(0);
}

/*
 * process - process input file
 */
process(in, inname)
FILE *in;
char *inname;
{
	char *nl, *files;
	char line[MAXLINE], msgid[MAXLINE], expiry[MAXLINE];
	char datercv[30];
	struct stat statb;
	static char msgidnm[] =  "Message-ID: ";
	static char expnm[] =    "Expires: ";
	register char *p;
	extern char *strrchr();
	extern char *strchr();
	extern char *strcpy();

	/* set defaults */
	(void) strcpy(expiry, "-");
	(void) strcpy(msgid, "<swill@trash>");

	/* read until EOF or blank line (end of headers) */
	while (fgets(line, sizeof line, in) != NULL && strcmp(line, "\n") != 0) {
		if ((nl = strrchr(line, '\n')) != NULL)
			*nl = '\0';			/* trim newline */
		if (strncmp(line, msgidnm, STRLEN(msgidnm)) == 0)
			(void) strcpy(msgid, line+STRLEN(msgidnm));
		else if (strncmp(line, expnm, STRLEN(expnm)) == 0)
			(void) strcpy(expiry, line+STRLEN(expnm));
	}

	/* generate the file name */
	files = inname;
	if (strncmp(files, spdir, spdirlen) == 0 &&
	    files[spdirlen] == '/')
		files += spdirlen + 1;	/* skip spool dir. & slash */

	/* generate the date received */
	(void) fstat(fileno(in), &statb);
	(void) sprintf(datercv, "%ld", statb.st_mtime);

	/* de-tab the message id */
	for (p = strchr(msgid, '\t'); p != NULL; p = strchr(p, '\t'))
		*p = ' ';

	/* whomp out the history line */
	(void) fputs(msgid, stdout);
	(void) putchar('\t');
	(void) fputs(datercv, stdout);
	(void) putchar('~');
	(void) fputs(expiry, stdout);
	(void) putchar('\t');
	(void) fputs(files, stdout);
	(void) putchar('\n');
	(void) fflush(stdout);
}

/*
 * unprivileged - no-op to keep pathname stuff happy
 */
void
unprivileged()
{
}
