#!/bin/rc
#uses MODELpid's namespace to remove all binds and mounts from TARGETpid that are not present in MODELpid's namespace

rfork e
ifs='
'
while (~ $1 -*){
	switch($1){
	case -o
		only=$2
		shift
		shift
	case -x
		xclude=$2
		shift
		shift
	case -t
		testonly=yes
		shift
	case -r
		riosafe=yes
		shift
	case *
		echo bad flag $1
		shift
	}
}

if(~ $2 ''){
	echo usage: subns MODELpid TARGETpid
	exit usage
	}
if(! test -e /proc/$1){
	echo process $1 does not exist!
	exit no.proc
}
if(! test -e /proc/$2){
	echo process $2 does not exist!
	exit no.proc
}
if(test -e /tmp/chnsuniq)
	rm /tmp/chnsuniq

orig=`{cat /proc/$2/ns}
for (i in $orig){
	search=''^$i^''
	match=`{cat /proc/$1/ns |grep -e $search}
	if(~ $match ''){
		echo $i >> /tmp/chnsuniq
	}
}
if(! test -e /tmp/chnsuniq){
	echo no binds in $2 not in $1 to subtract
	exit no.binds
}

sed 's/^/echo ⊞/g' /tmp/chnsuniq |sed 's/$/⊞ >\/proc\/'$2'\/ns/g'| tr ⊞ '''' |sed '/echo .cd/d' |sed 's/mount/unmount/g' | sed 's/bind/unmount/g' | sed 's/-. //g' |sed 's/-.. //g' |sed 's/  / /g' |sed '/\#\|\/data/d' |sed '/\#D\/ssl/d' |sed '/\#a\/tls/d' |sed '1!G;h;$!d' >/tmp/chnscom

if(~ $riosafe yes){
	cat /tmp/chnscom |sed '/\/mnt\/wsys/d' | sed '/\/mnt\/term/d' |sed '/\/dev\/cons/d' |sed '/rio/d' >/tmp/chnssafe
	mv /tmp/chnssafe /tmp/chnscom
}
if (! ~ $xclude ''){
	grep -v $xclude /tmp/chnscom >/tmp/chnssafe
	mv /tmp/chnssafe /tmp/chnscom
}
if (! ~ $only ''){
	grep $only /tmp/chnscom >/tmp/chnssafe
	mv /tmp/chnssafe /tmp/chnscom
}
if (test -e /tmp/chnssafe)
	rm /tmp/chnssafe
if(~ $testonly yes){
	cat /tmp/chnscom
	exit
}
. /tmp/chnscom

exit ''
