#!/bin/sh

declare -a COMMAND;
declare -i CPT_OLD;
declare -i CPT;
declare    FILE_CMD=;
declare    FILE_CPT=;
declare    FILE_CPU=;
declare    LOCK_CPT="${HOME}/.lock-cpt";
declare    LOCK_CPU="${HOME}/.lock-cpu";

#-----[ lock ]----------------------------------------------
function lock ()
{
    lockfile -1 $1;
}

#-----[ unlock ]--------------------------------------------
function unlock ()
{
    rm -f $1;
}

#-----[ main ]----------------------------------------------
function main ()
{
    # no test, because the script execute_n have make all test
    FILE_CMD=$1;
    FILE_CPT=$2;
    FILE_CPU=$3;

    lock   $LOCK_CPT;
    if test ! -s $FILE_CPT; then
	echo "0" > $FILE_CPT;
    fi;
    unlock $LOCK_CPT;

    # lit les fichiers ligne par ligne et le place dans un tableau
    CPT=0;

    while read line; do
	COMMAND[$CPT]="$line";
	CPT=$(($CPT+1));
    done < $1;

    echo "  * <$$> {"`date +"%F %T"`"} is ready";

    # infinite loop
    CPT_OLD=0;
    CPT=0;

    while test 1; do
	# Take a number
	CPT_OLD=$CPT;

	lock   $LOCK_CPT;
	CPT=`cat $FILE_CPT`;            # read  the      index
	echo "$(($CPT+1))" > $FILE_CPT; # write the next index
	unlock $LOCK_CPT;

	# test if this number is valid
	if test $CPT -ge ${#COMMAND[*]}; then
	    CPT=${#COMMAND[*]};
	fi;

	# test if between the cpt_old and cpt, there are a synchronisation command

#	local -i CPT_SYNC=$CPT_OLD;
#
#	while test $CPT_SYNC -lt $CPT; do
#	    if test -z "${COMMAND[$CPT_SYNC]}"; then
#		echo "  * <$$> {"`date +"%F %T"`"} synchronisation [$CPT_SYNC]";
#	    fi;
#	    CPT_SYNC=$(($CPT_SYNC+1));
#	done;

	# test if this number is valid
	if test $CPT -eq ${#COMMAND[*]}; then
	    break;
	fi;

	# Test if command is empty !
	if test ! -z "${COMMAND[$CPT]}"; then
	    local CUR_DIR=$PWD;

	    mkdir "Task_$CPT"       &> /dev/null;
	    cd    "Task_$CPT"       &> /dev/null;
	    echo "  * <$$> {"`date +"%F %T"`"} execute command [$CPT] : ${COMMAND[$CPT]}";
	    echo "${COMMAND[$CPT]}"  >  "command";
	    chmod +x                    "command";
	    eval "${COMMAND[$CPT]}" &>  "output";
	    cd    $CUR_DIR          &> /dev/null;
	fi;
    done;

    echo "  * <$$> {"`date +"%F %T"`"} is done";

    lock   $LOCK_CPU;
    CPT=`cat $FILE_CPU`;     # read  the      index
    CPT=$(($CPT-1));
    echo "$CPT" > $FILE_CPU; # write the next index
    unlock $LOCK_CPU;
    
    if test $CPT -eq 0; then
	echo "  * <$$> {"`date +"%F %T"`"} All task is executed";
	rm $FILE_CPU;
    fi;
}

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