#!/bin/bash
lescript=`basename $0 .sh`
flag=$TMP_PATH/bot_$lescript.flag

#
#  TOOLS
#
function debug
{
  if [ -f $FLAG_PATH/debug ]
  then
    echo $1
  fi
}

function sortie
{
  if [ -f $flag ]
  then
    rm -f $flag
  fi
  exit $1
}

function succes
{
  debug "SUCCES"
  sortie 0
}

function echec
{
  debug "ECHEC"
  sortie 1
}

#
# TEST DU FLAG
#
if [ -f $flag ]
then
  debug "$0 is already running !"
  exit 1
fi
touch $flag

#
# DO IT !
#
while IFS='' read -r line || [[ -n "$line" ]]; do
  NAME=`echo $line | awk '{print $1}'`
  BLOCK=`echo $line | awk '{print $2}'`
  HEIGHT=`echo $line | awk '{print $3}'`
  NBTX=`echo $line | awk '{print $4}'`

  #
  # On choisit la méthode qui découle du nonce
  #
  cd $APPS_PATH/nonce
  nbmethodes=`cat $DATA_PATH/nonce_methods_list.txt | wc -l`
  lenonce=`php robot.php $BLOCK`
  lamethode=$((lenonce % nbmethodes))
  if [ $lamethode -eq 0 ]
  then
	lamethode=$nbmethodes
  fi
  METHODE=`cat $DATA_PATH/nonce_methods_list.txt | head -n $lamethode | tail -1`
  echo $NAME $METHODE $lenonce $nbmethodes $lamethode
  if [ -f $DATA_PATH/$METHODE/$BLOCK.png ]
  then
    cp $DATA_PATH/$METHODE/$BLOCK.png $DATA_PATH/nonce/$BLOCK.png
  fi
done < $DATA_PATH/block_list.txt

rm -f $flag

#
# SORTIE AVEC SUCCES
#
succes

