#!/bin/rc

fn usage {
	echo 'usage: wctl=`{wctl [-c cmd] wsys}'
}

# Window creation

fn newwindow {
	srv = $wsys
	rfork ne
	{
		unmount /mnt/acme /dev >[2]/dev/null
		pid=`{cat /dev/ppid}
		if(mount -n $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 = $*
			echo -n `{basename $cmd(1)} > /dev/label >[2] /dev/null
			exec $cmd < /dev/cons > /dev/cons >[2] /dev/cons
		}
	}&
}

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

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

# Window deletion

fn killproc {
	rc -c '
		echo kill > /proc/'$1'/note
		sleep 0.2
		echo kill > /proc/'$1'/ctl
	' >[2] /dev/null &
}

fn killer {
	# mounts the root and blocks
	# reading from the kill file
	mount -n $wsys $dir / || exit
	cat $dir/kill | while (p=`{read}){
		killproc $p
	}
	killproc $1
}

# Serve at /srv/$1.pid

fn serve {
	srvname=$1
	shift
	# the fd 3 is used to get the pid
	# of the process run by srv
	srvpid=`{
		srv -eq '
			echo $pid >[1=3]
			{'^$"*^'} >[2] /dev/null
		' $srvname.$pid >[3=1] |
			read
	}
	mv /srv/$srvname.^($pid $srvpid) &&
		echo /srv/$srvname.$srvpid
}

# Main

cmd=(rio -i window)
if(~ $1 -c){
	if(~ $2 '')
		usage && exit
	cmd=`{echo $2}
	shift 2
}
if(! ~ $1 ''){
	wsys=$1
	shift
}
if(! ~ $#* 0)
	usage && exit
if(~ $wsys ''){
	echo 'wctl: $wsys not defined'
	exit
}

serve wctl.$user '
	dir = /mnt/wsys
	killer $pid &
	wctl
'
