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

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

#
# PARAMETRES PAR FICHIER FLAGS
#
if [ -f $FLAG_PATH/no_blocks ]
then
  debug "No blocks"
fi

BLOCK0=$1
if [ -z "$BLOCK" ]
then
    BLOCK0=`grep LAST $DATA_PATH/block_list.txt | awk '{print $2}'`
fi
echo $BLOCK0

pushd $APPS_PATH/info
infos=`php robot.php $BLOCK0`
HEIGHT=`echo $infos | awk '{print $1}'`
TIMETS=`echo $infos | awk '{print $2}'`
NBTX=`echo $infos | awk '{print $3}'`
NONCE=`echo $infos | awk '{print $4}'`
PREV=`echo $infos | awk '{print $5}'`
popd

#
# TEST DU FLAG
#
flag=$FLAG_PATH/bot_${lescript}_${BLOCK0}.flag
if [ -f $flag ]
then
  debug "${lescript}_${BLOCK0} already done"
fi
touch $flag

if [ -f $DATA_PATH/nonce/$BLOCK0.png ]
then
    echo COMPUTE IMAGE FOR $BLOCK0
    pushd $APPS_PATH >> /dev/null
    ./lancer2.sh block2 $BLOCK0
    popd >> /dev/null
fi
echo $DATA_PATH/nonce/$BLOCK0.png

BLOCK1=$PREV
pushd $APPS_PATH/info >> /dev/null
infos=`php robot.php $BLOCK1`
HEIGHT=`echo $infos | awk '{print $1}'`
TIMETS=`echo $infos | awk '{print $2}'`
NBTX=`echo $infos | awk '{print $3}'`
NONCE=`echo $infos | awk '{print $4}'`
PREV=`echo $infos | awk '{print $5}'`
popd >> /dev/null
if [ -f $DATA_PATH/nonce/$BLOCK1.png ]
then
    echo COMPUTE IMAGE FOR $BLOCK1
    pushd $APPS_PATH >> /dev/null
    ./lancer2.sh block2 $BLOCK1
    popd >> /dev/null
fi
echo $DATA_PATH/nonce/$BLOCK1.png

BLOCK2=$PREV
pushd $APPS_PATH/info >> /dev/null
infos=`php robot.php $BLOCK2`
HEIGHT=`echo $infos | awk '{print $1}'`
TIMETS=`echo $infos | awk '{print $2}'`
NBTX=`echo $infos | awk '{print $3}'`
NONCE=`echo $infos | awk '{print $4}'`
PREV=`echo $infos | awk '{print $5}'`
popd >> /dev/null
if [ -f $DATA_PATH/nonce/$BLOCK2.png ]
then
    echo COMPUTE IMAGE FOR $BLOCK2
    pushd $APPS_PATH >> /dev/null
    ./lancer2.sh block2 $BLOCK2
    popd >> /dev/null
fi
echo $DATA_PATH/nonce/$BLOCK2.png

pushd $APPS_PATH/triptyque >> /dev/null
php robot.php $BLOCK0 $BLOCK1 $BLOCK2
popd >> /dev/null
