/* udb.c - functions dealing with other users' UDB files
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "examine.h"
#include "bbs.h"

#define UDB_VARS_MAX	64

char *examine_udb__var[UDB_VARS_MAX];
char *examine_udb__val[UDB_VARS_MAX];
int examine_udb__size = 0;


/* Load the UDB file of "user" into memory, discarding previously loaded
 * data.
 */
void examine_udb_load(char *user)
{
	char buf[1024];
	FILE *fptr;
	char *a;
	int i;

	for (i = 0; i < examine_udb__size; i++) {
		free(examine_udb__var[i]);
		free(examine_udb__val[i]);
	}

	examine_udb__size = 0;

	strcpy(buf, cf_str("udb"));
	a = strrchr(buf, '/');
	if (!a)
		return;
	sprintf(a, "/%s", user);

	fptr = fopen(buf, "r");
	if (!fptr)
		return;

	while (!feof(fptr)) {
		buf[0] = 0;
		fgets(buf, sizeof(buf) - 1, fptr);
		if (examine_udb__size >= UDB_VARS_MAX)
			continue;
		a = strchr(buf, '\n');
		if (a)
			*a = 0;		    /* strip \n */
		a = strchr(buf, '=');
		if (!a)
			continue;
		*a = 0;
		a++;
		examine_udb__var[examine_udb__size] = strdup(buf);
		examine_udb__val[examine_udb__size] = strdup(a);
		examine_udb__size++;
	}

	fclose(fptr);
}


/* Save the UDB file of "user" from memory.
 */
void examine_udb_save(char *user)
{
	char buf[1024];
	FILE *fptr;
	char *a;
	int i;

	strcpy(buf, cf_str("udb"));
	a = strrchr(buf, '/');
	if (!a)
		return;
	sprintf(a, "/%s", user);

	fptr = fopen(buf, "w");
	if (!fptr)
		return;

	for (i = 0; i < examine_udb__size; i++) {
		fprintf(fptr, "%s=%s\n", examine_udb__var[i],
			examine_udb__val[i]);
	}

	fclose(fptr);
}


/* Return the value of UDB variable "var", or "" if it's not set.
 */
char *examine_udb_env(char *var)
{
	int i;

	for (i = 0; i < examine_udb__size; i++) {
		if (!strcmp(examine_udb__var[i], var))
			return (examine_udb__val[i]);
	}
	return ("");
}


/* Set the value of UDB variable "var" to "val".
 */
void examine_udb_env_set(char *var, char *val)
{
	int i;

	for (i = 0; i < examine_udb__size; i++) {
		if (!strcmp(examine_udb__var[i], var)) {
			free(examine_udb__val[i]);
			examine_udb__val[i] = strdup(val);
			return;
		}
	}

	examine_udb__var[examine_udb__size] = strdup(var);
	examine_udb__val[examine_udb__size] = strdup(val);
	examine_udb__size++;
}

/* EOF */
