#!/bin/rc
rfork ens
if(! ~ $#* 1){
	echo 'usage: run taskname'
	exit usage
}

T=$1  # job thema
if(! test -e $T/tasks){
	echo no tasks in $T
	exit usage
}

rm -rf $T/task.*.* >[2] /dev/null
glib=$home/lib/grid
dom=`{ls -p $glib}

# we select doms that we have factotum for
do=()
for(d in $dom){
	if(test -e $glib/$d/factotum)
		do=($do $d)
}
dom=$do

auth/factotum -n
for(d in $dom){
	read $glib/$d/factotum >/mnt/factotum/ctl
}

if(test -e /srv/taskfs){
	rm /srv/taskfs
	kill taskfs|rc
}
if(test -e $T/done)
	rm $T/done

bind -b bin/$objtype /bin
bind -b bin/rc /bin

srvfs -e /bin/taskfs taskfs $T
mount -bc /srv/taskfs /usr/none

cd /usr/none

# fn sighup is required to receive hangup signal
fn sighup{echo run: sighup}

# on exiting ...
fn sigexit{
	echo run: exiting ...
	if(test -e finish)
		. ./finish
	if(test -e done)
		rm done

	for(p in $mpids){
		if(test -e /proc/$p)
			echo kill >/proc/$p/notepg
	}
	# current dir has a reference of taskfs.
	# therefore we must "cd /" before killing taskfs
	# sleep is required because killing cpu has a time delay.
	sleep 3
	cd / ; kill taskfs|rc
	if(test -e /srv/taskfs)
		rm /srv/taskfs
	echo finished
}

mpids=()
ppid=$pid
for(d in $dom){
	hosts=`{grep -v '^#' $glib/$d/names}
	for(host in $hosts){
		echo login $host
		mrun $host &
		# debug
		if(! ~ $apid ?*)
			echo '# no $apid'
		mpids=($mpids $apid)
	}
}
#echo waiting $mpids
wait
