#!/bin/bash
flag=$TMP_PATH/twitterbot_bot.flag

if [ -f $flag ];
then
  echo "twitter_bot is already running !"
  exit 0
fi

touch $flag

cd $APPS_PATH/twitter/twitterbot

#
# Tweet pour un assemblage de hash
#
for fichier in `ls -tr $DATA_PATH/hashes2hashes/*.png`
do
  BLOCK_HASH=`basename $fichier .png`
done

if [ 5 -gt $((RANDOM % 100)) ]
then
  php robot.php $BLOCK_HASH CONFIRMED hashes2hashes
  touch $DATA_PATH/twitterbot/$BLOCK_HASH
fi

#
# Se lancer pour un tweet sur un block unique
#
BLOCK_LINE=`tail -n 1 $DATA_PATH/block_list.txt`
BLOCK_HASH=`echo ${BLOCK_LINE} | awk '{print $2}'`
BLOCK_NAME=`echo ${BLOCK_LINE} | awk '{print $1}'`
BLOCK_HEIGHT=`echo ${BLOCK_LINE} | awk '{print $3}'`

#
# Dans 5% des cas, on tweet un bloc remarquable
#      à la place du LAST
#
if [ 5 -gt $((RANDOM % 100)) ]
then
  BLOCK_LINE=`grep -v $BLOCK_NAME $DATA_PATH/block_list.txt | shuf | head -n 1`
  BLOCK_HASH=`echo ${BLOCK_LINE} | awk '{print $2}'`
  BLOCK_NAME=`echo ${BLOCK_LINE} | awk '{print $1}'`
  BLOCK_HEIGHT=`echo ${BLOCK_LINE} | awk '{print $3}'`
fi

if [ -f $DATA_PATH/hasard/$BLOCK_HASH.png ]
then
  echo Suppression $DATA_PATH/twitterbot/$BLOCK_HASH
  rm $DATA_PATH/twitterbot/$BLOCK_HASH
  if [ ! -f $DATA_PATH/twitterbot/$BLOCK_HASH ]
  then
    echo Tweet for $BLOCK_HASH $BLOCK_NAME
    echo php robot.php $BLOCK_HASH $BLOCK_NAME hasard $BLOCK_HEIGHT

    #
    # On met un marqueur pour ne pas retweeter
    #        plusieurs fois le LAST
    #
    if [[ "$BLOCK_NAME" == "LAST" ]]
    then
      touch $DATA_PATH/twitterbot/$BLOCK_HASH
    fi
  fi
fi

rm -f $flag
