/* This file is part of Mailfromd.
   Copyright (C) 2005-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 <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sysexits.h>

#include <mailutils/mailutils.h>
#include <mailutils/cli.h>
#include <mailutils/daemon.h>

#include "libmf.h"
#include "callout.h"
#include "srvman.h"
#include "srvcfg.h"
#include "mfdb.h"

void
callout_alloc_die()
{
	mu_error(_("not enough memory"));
        abort();
}

const char *program_version = "calloutd (" PACKAGE_STRING ")";
static char prog_doc[] = N_("calloutd -- a call out server");

static char *resolv_conf_file;

struct mu_cfg_param callout_cfg_param[] = {
 	{ ".mfd:server",  mu_cfg_section, NULL, 0, NULL, NULL },
	{ "resolver", mu_cfg_section, NULL, 0, NULL, NULL },
	{ NULL }
};



extern char **environ;

static char *capa[] = {
	"debug",
	"logging",
	"locking",
	".mfd:server",
	NULL
};

int
mf_server_function(const char *key, struct mf_srvcfg *cfg)
{
	cfg->server = callout_session_server;
	return 0;
}

static struct mu_option calloutd_options[] = {
	MU_OPTION_GROUP(N_("General options")),
	{ "resolv-conf-file", 0, N_("FILE"), MU_OPTION_DEFAULT,
	  N_("read resolver configuration from FILE"),
	  mu_c_string, &resolv_conf_file },
	MU_OPTION_END
}, *options[] = { calloutd_options, NULL };
	
struct mu_cli_setup cli = {
	.optv = options,
	.cfg = callout_cfg_param,
	.prog_doc = prog_doc,
};

int
main(int argc, char **argv)
{
	mf_init_nls();
	mf_proctitle_init(argc, argv, environ);
	mu_alloc_die_hook = callout_alloc_die;
	/* Set default logging */
	mu_log_facility = DEFAULT_LOG_FACILITY;
	mu_log_print_severity = 1;
	mu_stdstream_setup(MU_STDSTREAM_RESET_NONE);
	mf_srvcfg_log_setup(stderr_closed_p() ? "syslog" : "stderr");

	libcallout_init();
	db_format_setup();
	
	mf_server_save_cmdline(argc, argv);
	dnsbase_init();
	database_cfg_init();
	mu_acl_cfg_init();
	srvman_init();
	mf_srvcfg_init(argv[0], NULL);
	mf_getopt(&cli, &argc, &argv, capa, MF_GETOPT_DEFAULT);

	if (resolv_conf_file)
		dnsbase_file_init(resolv_conf_file);

	mf_srvcfg_flush();

	mf_server_lint_option = "--config-lint";
	mf_server_start("calloutd", mailfromd_state_dir, pidfile,
			server_flags);
	exit(0);
}
