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

static int ndev;
Dev *devtab[32];

void
adddev(Dev *d)
{
	int i;

	for(i=0; devtab[i]; i++)
		if(devtab[i]==d)
			return;

	if(ndev >= nelem(devtab)-1)
		pm_panic("too many devs");
	devtab[ndev++] = d;
	devtab[ndev] = nil;
	(*d->reset)();
}

void
pm_nsinit(void)
{
	adddev(&devroot);	/* must be first */
	adddev(&devdup);
	adddev(&devfs);
	adddev(&devcons);
	adddev(&devmnt);
	adddev(&devenv);
	adddev(&devsrv);

	up->slash = namec("#/", Atodir, 0, 0);
	cnameclose(up->slash->name);
	up->slash->name = newcname("/");

	if(bind("#U", "/", MBEFORE) < 0)
		pm_panic("bind in pm_nsinit failed: %r");
	bind("#c", "/dev", MBEFORE);
	bind("#e", "/env", MREPL|MCREATE);
	bind("#s", "/srv", MREPL|MCREATE);
	dprint(PmDebugFd, "dot is %s\n", up->dot->name->s);
}

int
readnum(ulong off, char *buf, ulong n, ulong val, int size)
{
	char tmp[64];

	snprint(tmp, sizeof(tmp), "%*.0lud", size-1, val);
	tmp[size-1] = ' ';
	if(off >= size)
		return 0;
	if(off+n > size)
		n = size-off;
	memmove(buf, tmp+off, n);
	return n;
}

int
readstr(ulong off, char *buf, ulong n, char *str)
{
	int size;

	size = strlen(str);
	if(off >= size)
		return 0;
	if(off+n > size)
		n = size-off;
	memmove(buf, str+off, n);
	return n;
}

