#!/bin/rc

# Usage
#	wctl=`{ wctl wsys [defaultcmd] }

fn window-m {
	dir = /mnt/wsys
	srv = $wsys
	rfork ne
	bind '#|' /n/pipe
	{
		unmount /mnt/acme /dev >[2]/dev/null
		pid=`{cat /dev/ppid}
		if(mount $srv $dir 'new -pid '^$pid^' '$"*){
			bind -b $dir /dev
			# toss geometry parameters to find command
			while(~ $1 -*)
				switch($1){
				case -dx -dy -minx -miny -maxx -maxy
					shift 2
				case -r
					shift 5
				case -scroll
					shift
				case -noscroll
					shift
				case -hide
					shift
				}
			if(~ $#* 0) cmd = $defaultcmd
			if not cmd = $*
			echo -n `{basename $cmd(1)} > /dev/label >[2] /dev/null
			if(test -f $dir/kill){
				f=/proc/^`{cat $dir/kill}^/note
				# the proces could have finished on
				# its own, check it is still there.
				if(test -f $f)
					echo kill > $f
			}&
			{exec cat /n/pipe/data1 > $dir/wctl}&
			exec $cmd < /dev/cons > /dev/cons >[2] /dev/cons
		}
	}&
	wait $apid && echo delete > /n/pipe/data
}

fn new {
	if(~ $1 -cd) {
		d=`{echo $2 | sed 's/-cd//'}
		cd $d
		shift 2
	}
	window-m $* &
}

fn wctl {
	while (a=`{read})
		if (~ $a(1) new) $a
}

defaultcmd=(rio -i window)
if(! ~ $1 ''){
	wsys=$1
	shift
}
if(~ $wsys ''){
	echo 'wctl: $wsys not defined'
	exit bad
}
if(! ~ $1 '')
	defaultcmd=$*

service=wctl.$user
# we want to know the pid of the wctl rc,
# so we use the fd 3 to send it from the
# rc runned by srv to this process.
srvpid=`{
	srv -eq '
		echo $pid >[1=3]
		wctl
	' $service.$pid >[3=1] |
		read
}
mv /srv/$service.^($pid $srvpid) &&
	echo /srv/$service.$srvpid
