#!/bin/bash
# Petit script pour poster l'Essentiel en allemand automatiquement
# FT20220604 
#########################################################

##########################
# initialize global variables
##########################
declare -a ur
declare -a db
declare -a post
declare -a txt
previous=EssDe.txt
maxpost=1
nbur=0
nbdb=0
nbpost=0

##########################
# read tags
##########################
xmlgetnext () {
local IFS='>'
read -d '<' TAG VALUE
}

##########################
# load previous posts
##########################
ReadDB_FT() {
while read -r line ; do
  db[$nbdb]=$line;
  nbdb=$((nbdb+1));
done < $previous

# trim db clean if ibigger than 100
if [ $nbdb -gt 100 ]; then
 tail -n +50 $previous > $previous.tmp && mv -f $previous.tmp $previous
fi

}

###########################
# get url and clean them ready for use
##########################
GetRSS_FT (){
Info=`curl --silent "https://www.lessentiel.lu/de" | while xmlgetnext ; do echo $TAG ; done | grep '^a href="/de/stor' | grep -v promi-tick `

for ind in 2 6 10 14 18 22 26 30 34 38 42 46 50 54 ; do
  t=`echo $Info | awk -v i=$ind '{print $i}'`
  ur[$nbur]="https://www.lessentiel.lu${t:6:${#t}-7}";
  nbur=$((nbur+1));
done
}

##########################
# here we check that the url hasn't been posted yet
# if it hasn't with prepare the text and put it on the pile to post 
# finally, we update the database
##########################
SortRSS_FT () {
  dejala=0;
for (( i=0; i < $nbur ; i++)); do
  for (( j=0; j < $nbdb ; j++)); do
   if  [[ "${ur[$i]}" = "${db[$j]}" ]] ; then
       dejala=1;
       break;
   fi
  done
   if [[ "$dejala" = "0" ]] ; then 
       post[$nbpost]=${ur[$i]};
       t=`echo ${ur[$i]} | cut -c36- `
       txt[$nbpost]=`echo ${t:0:${#t}-12} |sed 's/-/ /g'`
       nbpost=$((nbpost+1));
   else
     dejala=0;
   fi
done
}


##########################
# here we simply post by combining stuff
##########################
Post_FT () {
if [ $nbpost -gt 0 ]; then 
for (( i=0; i < $maxpost ; i++)); do
 line="L'Essentiel: ${txt[$i]} ${post[$i]} #news #Luxemburg";
 echo ${post[$i]} >> $previous
 madonctl toot $line
done
fi
}

#########################
ReadDB_FT
GetRSS_FT
SortRSS_FT
Post_FT
