#!/bin/bash

#
#  VARIABLES
#
export APPS_PATH=`dirname "$(readlink -f "$0")"`
export TMP_PATH=$APPS_PATH/../tmp
export DATA_PATH=$APPS_PATH/../data
export FLAG_PATH=$APPS_PATH/../flags

MINUTE=`date +%M | sed 's/^0*//'`
DATE=`date +%Y%m%d0000`

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

function sortie
{
  exit $1
}

function succes
{
  debug "SUCCES"
  sortie 0
}

function echec
{
  debug "ECHEC"
  sortie 1
}

# synchro de la blockchain
if [ -f $FLAG_PATH/no_blockchain ]
then
  debug "No Blockchain synchro"
else
  debug "Update the Blockchain"
  $APPS_PATH/blockchain/robot.sh 2>&1
  STATUS=$?
  if [ ! $STATUS -eq 0 ]
  then
    echec
  fi
fi

#
# Toujours placer la version HASHES
#
$APPS_PATH/methode/hashes/robot.sh

#
# CHOISIR UN MODE AU HASARD
#
ROBOT=`ls $APPS_PATH/methode | grep -v hashes | shuf | tail -n 1`
debug $ROBOT

#
# Y A PLUS QU'A !
#
if [ ! -f $FLAG_PATH/no_$ROBOT ]
then
  cd $APPS_PATH/methode/$ROBOT
  for BLOCK in `awk '{print $2}' $DATA_PATH/block_list.txt`
  do

    #
    # Pour renouveller l'affichage des blocs remarquables
    #   De temps en temps (15%), on efface le block
    #
    if [ $((RANDOM % 100)) -lt 15 ]
    then
      rm -f $DATA_PATH/$ROBOT/$BLOCK.png
    fi

    if [ ! -f $DATA_PATH/$ROBOT/$BLOCK.png ]
    then
      debug "Compute $DATA_PATH/$ROBOT/$BLOCK.png"
      php robot.php $BLOCK
    fi

    #
    # Les blocs remarquables sont anti datés à minuit
    #  Pour l'affichage et le nettoyage automatique 
    #
    BNAME=`grep $BLOCK $DATA_PATH/block_list.txt | awk '{print $1}'`
    if [ "$BNAME" != "LAST" ]
    then
      touch -t $DATE $DATA_PATH/$ROBOT/$BLOCK.png
    fi

    if [ ! -f $DATA_PATH/hasard/$BLOCK.png ]
    then
      ln $DATA_PATH/$ROBOT/$BLOCK.png $DATA_PATH/hasard/$BLOCK.png
    fi

  done
fi

#
# TWEET toutes les 20 minutes
#
if [ 0 -eq $TWEET ]
then
  debug "send a TWEET"
  # tweet R. Topisto
  $APPS_PATH/twitter/twitterbot/robot.sh 2>&1

  # "auto likes" from Topisto
  $APPS_PATH/twitter/likebot/robot.sh 2>&1
fi

#
# CLEAN OLD DATA
# 

if [ -d $DATA_PATH ]
then
	find $DATA_PATH -mtime +1 -type f -name *.png -exec rm -f {} \;
	find $DATA_PATH -mtime +1 -type f -name *.zip -exec rm -f {} \;
fi

rm -f $DATA_PATH/finished_block_list.txt
grep -v CACHE $DATA_PATH/block_list.txt >> $DATA_PATH/finished_block_list.txt

#
# SORTIE AVEC SUCCES
#
succes
