#include <9pm/windows.h>
#include <9pm/u.h>
#include <9pm/libc.h>
#include <9pm/ns.h>
#include <9pm/ctype.h>

static char*
wenv2env(Rune *r)
{
	char *s;
	Rune *rr;
	int len, n;

	len = 0;
	for(rr=r; *rr; rr+=runestrlen(rr)+1)
		len += runenlen(rr, runestrlen(rr))+1;
	len += 10;
	s = smalloc(len);
	n = 0;
	for(rr=r; *rr; rr+=runestrlen(rr)+1){
		win_wstr2utfn(s+n, len-n, rr);
		dprint(PmDebugNs, "'%s'\n", s+n);
		n += strlen(s+n)+1;
	}
	return s; 
}

/*
 * Only to be called at startup, hence no locks. 
 */
void
fillegrp(Egrp *g)
{
	LPWSTR wenv;
	char *env, *p, *q, *s;
	Evalue **l, *e;

	wenv = GetEnvironmentStrings();
	if(wenv == nil)
		return;
	env = wenv2env(wenv);
	FreeEnvironmentStrings(wenv);

	assert(g->entries == nil);
	l = &g->entries;
	for(p=env; *p; p+=strlen(p)+1){
		q = strchr(p, '=');
		if(q == nil)	/* shouldn't happen */
			continue;
		if(q == p)	/* windows has weird variables named with = */
			continue;
		*q = '\0';
		e = smalloc(sizeof(Evalue));
		e->name = smalloc(strlen(p)+1);
		e->value = smalloc(strlen(q+1)+1);
		strcpy(e->name, p);
		strcpy(e->value, q+1);
		e->len = strlen(e->value);
		/* windows variables are case insensitive; make 'em lower case */
	//	for(s=e->name; *s; s++)
	//		if(isupper(*s))
	//			*s = tolower(*s);
		e->qid.path = ++g->path;
		*q = '=';
		*l = e;
		l = &e->link;
	}
	*l = nil;
	free(env);
}

/* 
 * Should probably be locks here.
 * Then again we only call it in exec, which has
 * is in its own egrp, I believe.
 */
Rune*
_fetchegrp(Egrp *eg)
{
	int len, n;
	Evalue *e;
	Rune *r, *or;

	len = 0;
	for(e=eg->entries; e; e=e->link){
		len += utflen(e->name)+1+1;
		if(e->value)
			len += utflen(e->value);
	}
	len++;

	n = 0;
	r = smalloc(len*sizeof(Rune));
	or = r;
	for(e=eg->entries; e; e=e->link){
		win_utf2wstrn(r+n, len-n, e->name);
		n += runestrlen(r+n);
		r[n++] = '=';
		if(e->value){
			win_utf2wstrn(r+n, len-n, e->value);
			n += runestrlen(r+n);
		}
		r[n++] = '\0';
	}
	r[n++] = '\0';
	return or;
}
