#!/bin/rc
# change your current root and stay attached to window system and devices
# rerootwin targetsrv [ authagent ]

if(test -e /lib/namespace.saveterm)
	nsfile=/lib/namespace.saveterm
if(test -e /boot/namespace.saveterm)
	nsfile=/boot/namespace.saveterm
if(~ $nsfile ''){
	echo no namespace.saveterm found
	exit no.nssaveterm
}

pivot=/net.alt
while (~ $1 -*){
	switch($1){
	case -f
		nsfile=/boot/namespace.save9front
		if(test -e /lib/namespace.save9front)
			nsfile=/lib/namespace.save9front
	case -u
		pivot=/u
	case -n
		pivot=/n
	case -t
		nsfile=$2
		if(! test -e $2){
			echo nsfile $2 not found
			exit no.namespacefile
		}
		shift
	}
	shift
}
if(! ~ $1 ?*){
	echo need a target srv
	exit no.srv
}

# depending on the kind of namespace we are being run from we might need
# to get our devices in the expected place to begin

if(! test -e /mnt/wsys/wctl){
	if(! test -e /mnt/term/mnt/wsys/wctl){
		echo no wctl at mnt wsys
		exit no.wctl
	}
	echo binding /mnt/term/mnt/wsys to /mnt/wsys
	bind /mnt/term/mnt/wsys /mnt/wsys
}
if(! test -e /mnt/term/dev/cons){
	if(! test -e /mnt/wsys/cons){
		echo no cons at mnt term
		exit no.cons
	}
	if(! test -e /mnt/term/dev)
		mntgen /mnt/term
	echo binding /mnt/wsys /mnt/term/dev
	bind /mnt/wsys /mnt/term/dev
	if(! test -e /mnt/term/dev/draw)
		bind -a /dev /mnt/term/dev
}

if(! test -e /srv/$1){
	srv tcp!$1!564 $1
	if(! test -e /srv/$1){
		echo srv $1 couldnt be acquired
		exit no.srv
	}
}
nsroot=$1
if(~ $2 ?*){
	authagent=$2
}
if not if(! ~ $authagent ?*){
	authagent=factotum
}
if(! test -e /srv/$authagent){
	factotum -s $authagent
}
mount -b /srv/$authagent /mnt

# use srvfs to save our old devices so the namespace.saveterm can mount them later

oldterm=oldterm.$pid
oldwsys=oldwsys.$pid
srvfs -p 0600 oldterm.$pid /mnt/term
srvfs -p 0600 oldwsys.$pid /mnt/wsys

if(test -e /bin/newns){
	newns -n $nsfile
	exit ''
}

auth/newns -n $nsfile
exit ''
