/* This file is part of Mailfromd.
   Copyright (C) 2010-2025 Sergey Poznyakoff

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>. */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stdlib.h>
#include <string.h>
#include <mailutils/error.h>
#include <mailutils/stream.h>
#include <gettext.h>

#define DEFINE_BUILTIN_MODULE
#include "mailfromd.h"
#include "prog.h"
#include "builtin.h"

void
builtin_setup ()
{
	struct builtin_module *mod;
	for (mod = builtin_module; mod->name; mod++)
		if (mod->init)
			mod->init();
}

void
builtin_set_module_trace(const char *name, size_t len, int val)
{
	struct builtin_module *mod;
	
	for (mod = builtin_module; mod->name; mod++)
		if (strlen (mod->name) == len
		    && memcmp(mod->name, name, len) == 0) {
			mod->trace = val;
			return;
		}

	mu_error(gettext("no such module: %*.*s"), (int)len, (int)len, name);
}

void
builtin_set_all_module_trace(int val)
{
	struct builtin_module *mod;

	for (mod = builtin_module; mod->name; mod++)
		mod->trace = val;
}

int
builtin_module_trace(unsigned idx)
{
	return idx < BUILTIN_IDX_MAX && builtin_module[idx].trace;
}

void
_builtin_stream_cleanup(void *ptr)
{
	mu_stream_t str = ptr;
	mu_stream_unref(str);
}


mu_message_t
_builtin_mu_stream_to_message(mu_stream_t mstr, eval_environ_t env,
			      const char *func_name)
{
	int rc;
	mu_header_t hdr;
	mu_message_t msg;
	
	rc = mu_stream_to_message(mstr, &msg);
	if (rc)
		env_throw_bi(env, mfe_failure,
			     func_name,
			     "cannot obtain stream reference: %s",
			     mu_strerror(rc));
	mu_stream_unref(mstr);
	/* FIXME: This works over a bug in mailutils 2.99.92
	   <= release-2.2-378-g6060ab1 */
	mu_message_get_header(msg, &hdr);
	return msg;
}

int
_builtin_const_to_c(struct builtin_const_trans *tab, size_t count,
		    int num, int *ret)
{
	for (; count; tab++, count--)
		if (tab->const_mfl == num) {
			*ret = tab->const_c;
			return 0;
		}
	return -1;
}

int
_builtin_c_to_const(struct builtin_const_trans *tab, size_t count,
		    int num, int *ret)
{
	for (; count; tab++, count--)
		if (tab->const_c == num) {
			*ret = tab->const_mfl;
			return 0;
		}
	return -1;
}

int
_builtin_const_to_bitmap(struct builtin_const_trans *tab, size_t count,
			 int num)
{
	int f = 0;
	for (; count; tab++, count--)
		if (tab->const_c & num)
			f |= tab->const_mfl;
	return f;
}

