#!/bin/sh

#-----[ variable ]------------------------------------------
declare -a COMMAND;
declare -i NB_PROCESS;
declare -i CPT;
declare    FILE_CMD;
declare    FILE_CPT;
declare    FILE_CPU;
declare    ID="cpu-$HOSTNAME-$$"

#-----[ usage ]---------------------------------------------
function usage ()
{
    echo "Usage : $0 file [ nb_process ]";
    echo "      * file       : list of command";
    echo "      * nb_process : number of process (default (and maximum) is the number of processor)";
    echo "";
    echo "Note  - This script, for each command, create a directory : Task_X (X is the number of command), and execute the command in this directory.";
    echo "      - Two file is generate : \"output\" is the output of the execution, and \"command\" is the command lunch.";
    echo "      - A command empty (no command on a line of file1) is a synchronisation with all process"
    echo "      - Don't forgot the final end of line (else the last command is not executed";
    echo "";
    exit;
}

#-----[ nb_cpu ]--------------------------------------------
function nb_cpu ()
{
    local FILE_CPUINFO=/proc/cpuinfo;
    if test ! -f $FILE_CPUINFO; then
	echo "\"$FILE_CPUINFO\" don't exist."
	usage;
    fi;

    eval "$1=`grep -c \"processor\" $FILE_CPUINFO`";
}

#-----[ test_usage ]----------------------------------------
function test_usage ()
{
    if test $# -ne 1 -a $# -ne 2; then
	usage;
    fi;

    if test ! -f $1; then
	echo "File \"$1\" don't exist";
	usage;
    fi;

    if test ! -s $1; then
	echo "File \"$1\" is empty";
	usage;
    fi;
}

#-----[ main ]----------------------------------------------
function main ()
{
    nb_cpu NB_PROCESS;

    test_usage $*;

    if test $# -eq 2; then
	if test $2 -lt $NB_PROCESS; then
	    NB_PROCESS=$2;
	fi;
    fi;

    FILE_CMD=$1;
    FILE_CPT="$HOME/control-"`basename $1`;
    FILE_CPU="$HOME/$ID";

    echo "<$0>"                                         ;
    echo "  * Initialisation ...."                      ;
    echo "    - host name                : $HOSTNAME"   ;
    echo "    - number of process        : $NB_PROCESS" ;

    local -i IT_NB_PROCESS=1;
    local -i PID=$$;

    echo "$NB_PROCESS" > $FILE_CPU;

    # create the same number of thread that processor
    while test $IT_NB_PROCESS -le $NB_PROCESS; do
	execute.sh $FILE_CMD $FILE_CPT $FILE_CPU &
	IT_NB_PROCESS=$(($IT_NB_PROCESS+1));

	if test "$$" -ne $PID; then
	    break;
	fi;
    done
}

#-----[ Corps ]---------------------------------------------
main $*;
