/* envexp.c - expand environment variables in buffer
 */

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <pwd.h>
#include <sys/types.h>
#include <unistd.h>
#include "mstring.h"
#include "hook.h"


extern char *current_user;


/* Expand the environment variables referred to in "buf", whose maximum
 * length is "len" bytes.
 *
 * The following variables will automatically be set, regardless of their
 * value in the environment:
 *
 *   ACCOUNT        the current username
 *   MONO_ACCOUNT   the current username (for compatibility with Monochrome)
 *   NAMELINE       the current nameline, if set (blank string if not)
 *   KEYPATH        the current keypath, if known
 *   MONO_KEYPATH   the current keypath (for compatibility with Monochrome)
 *
 * NB Any $<prompt: > constructs will have to be expanded by the caller.
 */
void menu_envexpand(char *buf, long len)
{
	char *a;
	char c;
	int i;

	if (!buf)
		return;

	do {
		while ((buf[0] != 0) && (buf[0] != '$') && (len > 0)) {
			buf++;
			len--;
		}
		if (buf[0] != '$')
			return;
		i = 1;
		while (isalnum(buf[i]) || buf[i] == '_')
			i++;
		if (i < 2) {
			buf++;
			len--;
			continue;
		}
		c = buf[i];
		buf[i] = 0;
		if ((!strcmp(buf + 1, "MONO_ACCOUNT"))
		    || (!strcmp(buf + 1, "ACCOUNT"))) {
			a = current_user;
		} else if (!strcmp(buf + 1, "NAMELINE")) {
			a = getenv("MVIEW_NAMELINE");
			if (!a)
				a = "";
		} else if ((!strcmp(buf + 1, "MONO_KEYPATH"))
			   || (!strcmp(buf + 1, "KEYPATH"))) {
			a = "";
			bbs_hook(HOOK_GET_KEYPATH, &a, 0);
		} else {
			a = getenv(buf + 1);
		}
		buf[i] = c;
		if (a) {
			mstrdelete(buf, 0, i);
			i = 0;
			mstrinsert(buf, a, &i, len);
			buf += i;
			len -= i;
		} else {
			buf++;
			len--;
		}
	} while ((buf) && (len >= 0) && (buf[0] != 0));
}

/* EOF */
