/*
 * $Id: 31144969dab6dcd5ac8bc82cd65c0b431f7d1065 $
 *
 * This file is part of nsmtp.
 *
 * Copyright (c) 2007, 2008 Niklas Olmes <niklas@noxa.de>
 *                          http://www.nevm.de/nsmtp/
 *                          NEVM-RIPE
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2
 * as published by the Free Software Foundation.
 *
 * 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, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <syslog.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <time.h>
#include <signal.h>

#include "log.h"
#include "smtp.h"
#include "spool.h"
#include "misc.h"
#include "ntu.h"
#include "relay.h"
#include "greylist.h"
#include "alloc.h"
#include "proctitle.h"
#include "config.h"

static const char rcsid[] = "$Id: 31144969dab6dcd5ac8bc82cd65c0b431f7d1065 $";

static unsigned long long cycles;
static int n;
static int want_down = 0;

static void do_incoming(const char *, const char *);
static void do_defer(const char *, const char *);
static void sigterm(int);

static void
do_incoming(const char *subdir, const char *fn)
{
	char old[256], new[256], cleanfn[128];
	char *p;

	DEBUG(("do_incoming() => subdir <%s> file <%s>", subdir, fn));

	(void)snprintf(cleanfn, sizeof(cleanfn), "%s", fn);
	if ((p = strchr(cleanfn, '!')) != NULL)
		*p = '\0';

	(void)snprintf(old, sizeof(old), "%s/%s/%s", nsmc_spool_root, subdir, fn);
	if (n == 1)
		(void)snprintf(new, sizeof(new), "%s/active/%s", nsmc_spool_root, cleanfn);
	else
		(void)snprintf(new, sizeof(new), "%s/active/%ld/%s", nsmc_spool_root, (random() % n) + 1, cleanfn);

	/*
	 * NOTE: do_dir() ensures that files we get here are regular files
	 */

	if (chown(old, nsmc_smtps_uid, nsmc_smtps_gid) != 0) {
		xwarn("warn: do_incoming() => chown(%d, %d) for file <%s> failed: \"%s\"", nsmc_smtps_uid, nsmc_smtps_gid, old, strerror(errno));
		return;
	}
	if (chmod(old, 0660) != 0) {
		xwarn("warn: do_incoming() => chmod(0660) for file <%s> failed: \"%s\"", old, strerror(errno));
		return;
	}

	if (rename(old, new) != 0) {
		xwarn("warn: do_incoming() => rename(%s, %s) failed: \"%s\"", old, new, strerror(errno));
		return;
	}

	DEBUG(("do_incoming() => activated <%s>", cleanfn));
}

static void
do_defer(const char *subdir, const char *fn)
{
	SMTP_CTX *ctx;
	char old[256], new[256], cleanfn[128];
	char *p;
	int defercount;
	time_t defertime, curtime;

	DEBUG(("do_defer() => subdir <%s> file <%s>", subdir, fn));

	defercount = 0;
	defertime = 0;

	if ((p = strstr(fn, ";D=")) != NULL) {
		defercount = atoi(p+3);
		if ((p = strstr(fn, ";T=")) != NULL)
			defertime = atol(p+3);
		DEBUG(("do_defer() => found defercount (%d) and defertime (%lu) in <%s>", defercount, defertime, fn));

		curtime = time(NULL);
		if (defertime == 0 || (defercount+1)*(defercount+1) * 60 + defertime < curtime) {
			DEBUG(("do_defer() => we found that we should UNPARK <%s>", fn));
		} else {
			DEBUG(("do_defer() => it seems <%s> has to wait", fn));
			return;
		}
	} else
		xwarn("warn: do_defer() => no defer count found on <%s>, assuming we should UNPARK", fn);

	if ((ctx = read_spoolfile(subdir, fn)) == NULL) {
		xwarn("warn: do_defer() => unable to read file: spool subdir <%s>, file <%s>", subdir, fn);
		return;
	}

	if (ctx->rcpts != NULL && ctx->rcpts[0] != NULL) {
		xwarn("warn: do_defer() => sanity check failed:  there are rcpts left in <%s>, subdir <%s>, this should not be", fn, subdir);
		goto error_out;
	}
	if (ctx->defers == NULL || ctx->defers[0] == NULL) {
		xwarn("warn: do_defer() => sanity check failed:  there are no defers in <%s>, subdir <%s>, this makes no sense", fn, subdir);
		goto error_out;
	}

	if (ctx->rcpts != NULL)
		nsm_free(ctx->rcpts);

	ctx->rcpts = ctx->defers;
	ctx->defers = NULL;
	if (update_spool(subdir, fn, ctx) != 0) {
		xwarn("warn: do_defer() => update_spool() failed on <%s>, subdir <%s>, this should not happen", fn, subdir);
		goto error_out;
	}

	(void)snprintf(cleanfn, sizeof(cleanfn), "%s", fn);
	if ((p = strchr(cleanfn, '!')) != NULL)
		*p = '\0';

	(void)snprintf(old, sizeof(old), "%s/%s/%s", nsmc_spool_root, subdir, fn);
	if (n == 1)
		(void)snprintf(new, sizeof(new), "%s/active/%s", nsmc_spool_root, cleanfn);
	else
		(void)snprintf(new, sizeof(new), "%s/active/%ld/%s", nsmc_spool_root, (random() % n) + 1, cleanfn);

	if (rename(old, new) != 0) {
		xwarn("warn: do_defer() => rename(%s, %s) failed: \"%s\"", old, new, strerror(errno));
		goto error_out;
	}

	xinfo("info: {%s}|%s| UNPARKED activated, defer count (%d), defer time (%lu)", ctx->conn_id, ctx->lmid, defercount, defertime);

error_out:
	destroy_smtp_ctx(ctx);
}

static void
sigterm(int ignore)
{

	(void)ignore;
	want_down = 1;
}

int
main(int argc, char *argv[])
{
	const char *cfgfile;
	int ch;

	setprogname(argv[0]);
	cfgfile = NSMTP_DEFAULT_CONFIG;

	while ((ch = getopt(argc, argv, "c:hv")) != -1)
		switch (ch) {
		case 'c':
			cfgfile = optarg;
			break;
		case 'v':
			(void)fprintf(stderr, "nsmtp Version %s\n", NSMTP_VERSION);
			(void)fprintf(stderr, "Copyright (c) 2007, 2008 Niklas Olmes <niklas@noxa.de>\n"
				      "                         http://www.nevm.de/nsmtp/\n"
				      "                         NEVM-RIPE\n"
				      "Licensed under the GNU GPL Version 2.\n");
			exit(EXIT_SUCCESS);
		case '?': /* FALLTHRU */
		case 'h': /* FALLTHRU */
		default:
			(void)fprintf(stderr, "Usage: %s [-c cfgfile] [-hv] n\n", getprogname());
			(void)fprintf(stderr, "\tn = 1:  spool for just one slave pair in active/, no concurrency\n"
					      "\tn > 1:  n concurrent slave pairs in active/x/, 1 <= x <= n\n");
			exit(EXIT_FAILURE);
		}

	if (argc - optind != 1) {
		(void)fprintf(stderr, "Usage error:  Missing parameter n on command line.\n");
		(void)fprintf(stderr, "%s -h for Usage.\n", getprogname());
		exit(EXIT_FAILURE);
	}

	if ((n = atoi(argv[optind])) < 1 || n > 1000) {
		(void)fprintf(stderr, "numslaves (%d) out of range\n", n);
		exit(EXIT_FAILURE);
	}

	openlog("nsmtp(smtps)", LOG_PID, LOG_MAIL);
	if (nsm_config_read(cfgfile) != 0)
		nsm_config_perror("smtps");
	xinfo("info: nsmtp smtps started for n=(%d)", n);

	(void)signal(SIGTERM, sigterm);

	ntu_seed();
	daemonize();
	write_pid_file("smtps");

	initproctitle(argc, argv);
	setproctitle("started");

	cycles = 0;
	while (!want_down) {
		if (cycles && cycles % 10000 == 0)
			xinfo("info: still alive after (%llu) cycles", cycles);

		setproctitle("incoming");
		do_dir("incoming", do_incoming);

		if (cycles % 10 == 0) {
			setproctitle("@%lu defers", time(NULL));
			do_dir("defer", do_defer);
		}

		if (cycles % 50 == 0) {
			setproctitle("@%lu cleanup relay", time(NULL));
			cleanup_relay();
		}

		if (cycles % 4000 == 0) {
			setproctitle("@%lu cleanup greylist rcpt", time(NULL));
			cleanup_greylist_rcpt();
		}

		if (cycles % 5000 == 0) {
			setproctitle("@%lu cleanup greylist spf", time(NULL));
			cleanup_greylist_spf();
		}

		if (cycles % 7000 == 0) {
			setproctitle("@%lu cleanup whitelist host", time(NULL));
			cleanup_whitelist_host();
		}

		setproctitle("idle");
		(void)sleep((unsigned int)((random() % 10) + 2));
		++cycles;
	}

	xinfo("info: SIGTERM received, shutdown");

	nsm_config_free();

	xinfo("info: shutdown complete");

	exit(EXIT_SUCCESS);
}
