#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

/*
 *    Code (C) F6FBB 1995-1996
 *
 *  M_FILTER example for 7plus files.
 *
 *  Answers go to stdout.
 *
 *  This code is only an example and was not fully tested. It could
 *  give problems as I am not an expert !
 *
 * Parameters are (for M_FILTER):
 * ac[0] : The name of the filter (M_FILTER)
 * ac[1] : The name of the file holding the message
 * ac[2] : The type of the message (P,B, etc...)
 * ac[3] : The sender
 * ac[4] : The destination
 * r_buf : The buffer to put an answer (NULL for M_FILTER)
 * len   : The size of the answer buffer (0 for M_FILTER)
 *
 * Return value (for M_FILTER):
 * 0 : Message is accepted
 * 1 : Message is killed (Status K)
 * 2 : Message is archived (Status A)
 * 3 : Message is hold
 *
 */

int main (int ac, char ** av)
{
	static char *pattern = "_7+";

	int pos;
	int match;
	int nb;
	int hptr_m;
	int hptr_d;
	int found = 0;
	char buffer[512];

	if (ac < 2)
		return (0);

	hptr_m = open (av[1], O_RDONLY, S_IREAD|S_IWRITE);
	if (hptr_m == -1)
		return (0);

	nb = 0;
	match = 0;
	pos = 0;

	/* Scans the input file to find the pattern */
	for (;;)
	{
		if (pos == nb)
		{
			nb = read (hptr_m, buffer, sizeof (buffer));
			if (nb <= 0)
				break;
			pos = 0;
		}
		if (buffer[pos] == pattern[match])
		{
			if (pattern[++match] == '\0')
			{
				found = 1;
				break;
			}
		}
		else
			match = 0;
		++pos;
	}

	if (found)
	{
		/* The pattern has been found. This is a 7+ file */
		hptr_d = open ("m_filter.fwd", O_APPEND|O_CREAT|O_WRONLY, S_IREAD|S_IWRITE);
		if (hptr_d == -1)
			return (0);

		lseek (hptr_m, 0, 0);
		lseek (hptr_d, 0, 2);

		/* The message is appended to the "m_filter.fwd" file */
		sprintf (buffer, "S%s %s < %s\r\n", av[2], av[4], av[3]);
		write (hptr_d, buffer, strlen (buffer));
		sprintf (buffer, "No title\r\n");
		write (hptr_d, buffer, strlen (buffer));
		while ((nb = read (hptr_m, buffer, sizeof (buffer))) > 0)
		{
			write (hptr_d, buffer, nb);
		}
		sprintf (buffer, "/EX\r\n");
		write (hptr_d, buffer, strlen (buffer));

		close (hptr_d);

	}

	close (hptr_m);
	return (0);
}
