
#include <stdlib.h>
#include "antispam-plugin.h"
#include "mail-storage-private.h"

int signature_extract_to_list(const struct antispam_settings *cfg,
			      struct mailbox_transaction_context *t,
			      struct mail *mail, struct siglist **list,
			      enum classification wanted)
{
	const char *const *signatures;
	struct siglist *item;

	signatures = get_mail_headers(mail, cfg->signature);
	if (!signatures || !signatures[0]) {
		if (!cfg->signature_missing_ok) {
			mail_storage_set_error(t->box->storage,
					       MAIL_ERROR_NOTPOSSIBLE,
					       "antispam signature not found");
			return -1;
		} else {
			return 0;
		}
	}

	while (signatures[1])
		signatures++;

	item = i_new(struct siglist, 1);
	item->next = *list;
	item->wanted = wanted;
	item->sig = i_strdup(signatures[0]);

	*list = item;

	return 0;
}

int signature_extract(const struct antispam_settings *cfg,
		      struct mailbox_transaction_context *t,
		      struct mail *mail, const char **signature)
{
	const char *const *signatures;

	signatures = get_mail_headers(mail, cfg->signature);
	if (!signatures || !signatures[0]) {
		if (!cfg->signature_missing_ok) {
			mail_storage_set_error(t->box->storage,
					       MAIL_ERROR_NOTPOSSIBLE,
					       "antispam signature not found");
			return -1;
		} else {
			*signature = NULL;
			return 0;
		}
	}

	while (signatures[1])
		signatures++;

	*signature = signatures[0];

	return 0;
}

void signature_list_free(struct siglist **list)
{
	struct siglist *item, *next;

	i_assert(list);

	item = *list;

	while (item) {
		next = item->next;
		i_free(item->sig);
		i_free(item);
		item = next;
		if (item)
			next = item->next;
	}
}
