/* $Id: conf.c,v 1.31 2015/09/29 13:17:42 onoe Exp $ */

/*-
 * Copyright (c) 1998-1999 Atsushi Onoe
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "cue.h"

static int
conf_get_num(const char *p, int *nump, int *decp)
{
	int num, dec;
	char *q;

	num = strtol(p, &q, 10);
	if (p == q)
		return 0;
	p = q;
	dec = 0;
	if (decp != NULL) {
		if (*p == '/') {
			dec = strtol(p + 1, &q, 10);
			if (p + 1 == q)
				return 0;
			p = q;
		}
	}
	if (*p != '\0')
		return 0;
	*nump = num;
	if (decp != NULL)
		*decp = dec;
	return 1;
}

static int
conf_get_bool(const char *p, int *boolp)
{

	if (strcasecmp(p, "on") == 0
	||  strcasecmp(p, "true") == 0
	||  strcmp(p, "1") == 0) {
		*boolp = 1;
		return 1;
	}
	if (strcasecmp(p, "off") == 0
	||  strcasecmp(p, "false") == 0
	||  strcmp(p, "0") == 0) {
		*boolp = 0;
		return 1;
	}
	return 0;
}

static int
conf_get_str(const char *p, char **valp)
{
	char *q;

	if (*valp)
		free(*valp);
	if (p == NULL) {
		*valp = NULL;
		return 1;
	}
	*valp = strdup(p);
	if (*valp == NULL)
		return 0;
	/* XXX: compatibility: %d -> %s */
	while ((q = strstr(*valp, "%d")) != NULL)
		q[1] = 's';
	return 1;
}

static void
conf_default(struct config *config)
{
	struct refile_list *rl, *nrl;
	struct clist *cl, *ncl;

	for (rl = config->refile_list; rl; rl = nrl) {
		nrl = rl->next;
		free(rl->hdr.ptr);
		free(rl->pat.ptr);
		if (rl->fol.ptr)
			free(rl->fol.ptr);
		free(rl);
	}
	config->refile_list = NULL;
	for (cl = config->myaddr; cl; cl = ncl) {
		ncl = cl->next;
		free(cl->buf.ptr);
		free(cl);
	}
	config->myaddr = NULL;

	/* default */
	conf_get_str(DEF_INC, &config->inc);
	conf_get_str(NULL, &config->bcc);
	conf_get_str(DEF_SEND, &config->send);
	conf_get_str(DEF_EDITOR, &config->editor);
	conf_get_str(DEF_FOLDER, &config->folder);
	conf_get_str(DEF_SPAM, &config->spam);
	config->numwidth = DEF_NUMWIDTH;;
	conf_get_num(DEF_WINSIZE, &config->lines, &config->linesall);
	config->disptime = FALSE;
	conf_get_str(DEF_STATFILE, &config->statfile);
	conf_get_str(DEF_MAILCAP, &config->mailcap);
	config->addrbook = NULL;
	config->statbackup = DEF_STATBACKUP;
}

static void
conf_read(struct state *state)
{
	FILE *fp;
	char buf[MAXPATH];
	struct refile_list *rl, **rlp;
	struct clist *cl;
	char *p, *cmd;
	enum { DEFAULT, REFILE } part;
	int lno;
	struct config *config = &state->config;

	if (config->path == NULL || (fp = fopen(config->path, "r")) == NULL)
		return;

	rlp = &config->refile_list;
	part = DEFAULT;
	rl = NULL;
	lno = 0;
	while (fgets(buf, sizeof(buf), fp)) {
		lno++;
		if (*buf == '#' || *buf == '\n')
			continue;
		if ((p = strchr(buf, '\n')))
			*p = '\0';
		if (*buf == '%') {
			if (strcmp(buf + 1, "refile") == 0)
				part = REFILE;
			else
				part = DEFAULT;
			continue;
		}
		switch (part) {
		case DEFAULT:
			if ((cmd = strtok(buf, ":")) == NULL
			||  (p = strtok(NULL, "")) == NULL)
				goto cmderr;
			while (*p == ' ' || *p == '\t')
				p++;
			if (strcmp(cmd, "inc") == 0) {
				if (!conf_get_str(p, &config->inc))
					goto cmderr;
				break;
			}
			if (strcmp(cmd, "send") == 0) {
				if (!conf_get_str(p, &config->send))
					goto cmderr;
				break;
			}
			if (strcmp(cmd, "editor") == 0) {
				if (!conf_get_str(p, &config->editor))
					goto cmderr;
				break;
			}
			if (strcmp(cmd, "bcc") == 0) {
				if (!conf_get_str(p, &config->bcc))
					goto cmderr;
				break;
			}
			if (strcmp(cmd, "initial_folder") == 0) {
				if (!conf_get_str(p, &config->folder))
					goto cmderr;
				break;
			}
			if (strcmp(cmd, "spam_folder") == 0) {
				if (!conf_get_str(p, &config->spam))
					goto cmderr;
				break;
			}
			if (strcmp(cmd, "myaddr") == 0) {
				for (; (p = strtok(p, ", \t")); p = NULL) {
					cl = malloc(sizeof(*cl));
					cl->buf.ptr = strdup(p);
					cl->buf.len = strlen(p);
					cl->next = config->myaddr;
					config->myaddr = cl;
				}
				break;
			}
			if (strcmp(cmd, "msgnum_width") == 0) {
				if (!conf_get_num(p, &config->numwidth, NULL))
					goto cmderr;
				break;
			}
			if (strcmp(cmd, "initial_window_size") == 0) {
				if (!conf_get_num(p, &config->lines,
				    &config->linesall))
					goto cmderr;
				break;
			}
			if (strcmp(cmd, "disp_time") == 0) {
				if (!conf_get_bool(p, &config->disptime))
					goto cmderr;
				break;
			}
			if (strcmp(cmd, "status_file") == 0) {
				if (!conf_get_str(p, &config->statfile))
					goto cmderr;
				break;
			}
			if (strcmp(cmd, "status_backup") == 0) {
				if (!conf_get_bool(p, &config->statbackup))
					goto cmderr;
				break;
			}
			if (strcmp(cmd, "mailcap") == 0) {
				if (!conf_get_str(p, &config->mailcap))
					goto cmderr;
				break;
			}
			if (strcmp(cmd, "addrbook") == 0) {
				if (!conf_get_str(p, &config->addrbook))
					goto cmderr;
				break;
			}
  cmderr:
			snprintf(state->status, sizeof(state->status),
			    "%s: line %d: command format error",
			    config->path, lno);
			break;
		case REFILE:
			rl = malloc(sizeof(*rl));
			rl->next = NULL;
			for (p = buf; *p != '\0'; p++) {
				if (*p != ' ' && *p != '\t')
					break;
			}
			if ((rl->hdr.ptr = strtok(p, "\t")) == NULL
			||  (rl->pat.ptr = strtok(NULL, "\t")) == NULL) {
				snprintf(state->status, sizeof(state->status),
				    "%d: refile format error", lno);
				free(rl);
				break;
			}
			rl->hdr.len = strlen(rl->hdr.ptr);
			rl->hdr.ptr = strdup(rl->hdr.ptr);
			rl->pat.len = strlen(rl->pat.ptr);
			rl->pat.ptr = strdup(rl->pat.ptr);
			if ((rl->fol.ptr = strtok(NULL, "\t")) != NULL) {
				rl->fol.len = strlen(rl->fol.ptr);
				rl->fol.ptr = strdup(rl->fol.ptr);
			} else
				rl->fol.len = 0;
			*rlp = rl;
			rlp = &rl->next;
			break;
		}
	}
	fclose(fp);
}

/*
 * XXX modify exec path
 */
static void
conf_addpath(char *add)
{
	char *path, *opath;
	int ret;

	opath = getenv("PATH");
	if (opath == NULL)
		ret = asprintf(&path, "PATH=%s", add);
	else
		ret = asprintf(&path, "PATH=%s:%s", opath, add);
	if (ret < 0)
		return;
	putenv(path);
	/*
	 *	free(path);
	 * Some of the putenv() implementations, e.g. SVR4, don't
	 * duplicate argument of putenv, but just use the pointer.
	 * So we don't free the argument here.
	 */
}

void
conf_update(struct state *state)
{
	struct stat statbuf;
	struct config *config = &state->config;

	if (config->path == NULL) {
		asprintf(&config->path, "%s/%s", getenv("HOME"), CONFFILE);
		conf_addpath("/usr/lib");	/* XXX for sendmail */
	}
	if (stat(config->path, &statbuf) < 0) {
		if (!config->notfound) {
			config->notfound = 1;
			conf_default(config);
		}
		return;
	}
	if (config->notfound
	||  config->statbuf.st_ino != statbuf.st_ino
	||  config->statbuf.st_mtime != statbuf.st_mtime
	||  config->statbuf.st_size != statbuf.st_size) {
		config->notfound = 0;
		config->statbuf = statbuf;
		conf_default(config);
		conf_read(state);
	}
}

int
conf_myaddr(struct state *state, ccbuf_t *buf)
{
	struct clist *cl;
	int len;

	len = buf->len;
	for (cl = state->config.myaddr; cl; cl = cl->next) {
		if (cl->buf.len == len
		&&  strncasecmp(cl->buf.ptr, buf->ptr, len) == 0)
			return 1;
	}
	return 0;
}
