#!/bin/bash

# tested successfully on bash 3.2 under Freebsd 7.0

# le but est ici de lancer plusieurs rsync en parrallele,
# d'attendre leur fin, de connaitre leur code d'erreur

set -o allexport
declare -ax PNlist
declare -ax Exlist

# se charge d'executer en arriere plan et de renvoyer le pid
# en plus cela doit loguer
function launch {
	# on execute
	$2 $3 2>&1 > $1.log &
	# enregistre le pid et le nom
	PNlist[$!]="$1"
}

# fonction event handler
function tr_child {
	# chaque fois que je recois un fils mort
	# je kill -0 chacun pour determiner quel fils est mort
	for pid in ${!PNlist[*]}; do
		# et une tache externe ! Une ! donc un SIGCHLD ! Hein !
		if ( ! kill -0 $pid 2>/dev/null ); then
			jobs -l | while read jobid jpid state info more; do
				if [ "$jpid" == "$pid" ]; then
					case "$state" in 
						"Exit")
							Exlist[$pid]="${PNlist[$pid]} $info"
							;;
						"Done")
							Exlist[$pid]="${PNlist[$pid]} 0"
							;;
					esac
				fi
			done
			unset PNlist[$pid]
			return
		fi
	done
}

# instruit le trap handler pour recuperer les fils
set -o monitor
trap tr_child SIGCHLD

# lance les X commandes
# le faire avec des identifiants, comme cela je pourrai retrouver
# qui est qui a la fin, et dire quel a eu quoi si probleme
launch tota /usr/users/eak/moa/tcl/dumb-doing.tcl tota
launch tote /usr/users/eak/moa/tcl/dumb-doing.tcl tote
launch toty /usr/users/eak/moa/tcl/dumb-doing.tcl arf
launch totu /usr/users/eak/moa/tcl/dumb-doing.tcl totu
launch toti /usr/users/eak/moa/tcl/dumb-doing.tcl toti
launch toto /usr/users/eak/moa/tcl/dumb-doing.tcl toto

if [ "$1" == "-v" ]; then
	# on affiche ce qu'il y a
	for pid in ${!PNlist[*]} ; do
		echo "$pid ${PNlist[$pid]}"
	done
fi

wait

End=0
for pid in ${!Exlist[*]}; do
	echo $pid ${Exlist[$pid]}
	#exitcode=${PNlist[$pid]/* /}
	#if [ $existcode -ne 0 ]; then
	#	End=1
	#fi
done

exit $End

