#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "conf.h"

static char *
trim(char *s)
{
	char *e;

	while (isspace((unsigned char)*s))
		s++;
	e = s + strlen(s);
	while (e > s && isspace((unsigned char)e[-1]))
		*--e = '\0';
	return s;
}

int
conf_load(struct conf *cf, const char *path)
{
	FILE *f;
	char line[1024], *eq, *k, *v;

	memset(cf, 0, sizeof(*cf));
	if ((f = fopen(path, "r")) == NULL)
		return -1;
	while (fgets(line, sizeof(line), f) != NULL && cf->n < CONF_MAX) {
		k = trim(line);
		if (*k == '#' || *k == '\0' || (eq = strchr(k, '=')) == NULL)
			continue;
		*eq = '\0';
		/* trailing comment: whitespace followed by '#' */
		for (v = eq + 1; *v; v++)
			if (*v == '#' && isspace((unsigned char)v[-1])) {
				*v = '\0';
				break;
			}
		k = trim(k);
		v = trim(eq + 1);
		cf->keys[cf->n] = strdup(k);
		cf->vals[cf->n] = strdup(v);
		cf->n++;
	}
	fclose(f);
	return 0;
}

const char *
conf_get(const struct conf *cf, const char *key, const char *def)
{
	int i;

	for (i = 0; i < cf->n; i++)
		if (strcmp(cf->keys[i], key) == 0)
			return cf->vals[i];
	return def;
}

static const char *
next_item(const char *p, size_t *len)
{
	while (*p == ',' || isspace((unsigned char)*p))
		p++;
	/* Commas separate groups; spaces may be part of an LDAP group name. */
	*len = strcspn(p, ",");
	while (*len > 0 && isspace((unsigned char)p[*len - 1]))
		(*len)--;
	return *len ? p : NULL;
}

int
list_has(const char *list, const char *item)
{
	const char *p = list;
	size_t len, ilen = strlen(item);

	if (list == NULL || ilen == 0)
		return 0;
	while ((p = next_item(p, &len)) != NULL) {
		if (len == ilen && strncmp(p, item, len) == 0)
			return 1;
		p += len;
	}
	return 0;
}

int
list_intersects(const char *a, const char *b)
{
	const char *p = a;
	size_t len;
	char item[128];

	if (a == NULL || b == NULL)
		return 0;
	while ((p = next_item(p, &len)) != NULL) {
		if (len < sizeof(item)) {
			memcpy(item, p, len);
			item[len] = '\0';
			if (list_has(b, item))
				return 1;
		}
		p += len;
	}
	return 0;
}
