#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include "oopsd.h"

/* Code to mail an oops report. */
int mail_oops(const char *filename)
{
	FILE *mailer;
	int r, input;
	char buffer[512 + 1];

	/* FIXME: Use O_DIRECT, in case we haven't rebooted. */
	input = open(filename, O_RDONLY);
	if (input < 0) {
		fprintf(stderr, "Failed to open %s: %s",
			filename, strerror(errno));
		return 0;
	}
	mailer = popen("/usr/bin/mail -s OOPS -a 'Reply-To: oops@rustcorp.com.au' 'Whoever is in charge of this machine <root>'", "w");
	if (!mailer) {
		perror("Failed to run /usr/bin/mail");
		close(input);
		return 0;
	}

	/* FIXME: May not be "hard drive": pass in as param? */
	fprintf(mailer,
		"Hi!\n"
		"	I found a kernel Oops report on your hard drive.\n"
		"This probably means your computer crashed recently: I like\n"
		"to collect these reports to help find Linux bugs, and you\n"
		"can see the results below.\n"
		"	To send this report to the Oops Team, just reply to\n"
		"this message (with the whole text quoted), or forward this\n"
		"mail to oops@rustcorp.com.au.  Otherwise, just delete it!\n"
		"\n"
		"Thanks for your help!\n"
		"Rusty Russell,\n"
		"Oops Collector.\n");
	fprintf(mailer, "\n");

	fprintf(mailer, "=== V0.1: Cut here for Oops report start ===\n");
	/* Automatically strips NUL chars from each sector. */
	while ((r = read(input, buffer, sizeof(buffer)-1)) > 0) {
		buffer[r] = '\0';
		fprintf(mailer, "%s", buffer);
	}
	fprintf(mailer, "=== Cut here for Oops report end ===\n");
	pclose(mailer);
	close(input);

	return 1;
}
	




