#!/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
  #
  # On choisit la méthode qui découle du nonce
  #
  cd $APPS_PATH/nonce
  nbmethodes=`ls $APPS_PATH/methode2 | grep -v robot | wc -l`
  lenonce=`php robot.php $BLOCK`
  lamethode=$((lenonce%nbmethodes))
  [ $lamethode -eq 0 ] ; lamethode=$nbmethodes
  METHODE=`ls $APPS_PATH/methode2 | grep -v robot | head -n $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

#
# SORTIE AVEC SUCCES
#
succes
