#!/bin/bash
###################################################################
#                                                                 #
#  Get song info and download lyrics from database.               #
#  Depends on: wget                                               #
#                                                                 #
#  Scripted by Koentje   (remon@cobrasoft.nl)                     #
#                                                    version 1.3  #
###################################################################

if ! [ -f "./tempfiles/player.running" ]; then exit; fi

txtfile="./tempfiles/lyrics.txt"
tmpfile="./tempfiles/lyrics.tmp"
outfile="./tempfiles/lyrics.out"
cfgfile="./show-lyric.ini"
source "$cfgfile"

if ! [ -f "$txtfile" ]; then exit; fi


sendmsg () {
   echo -e "\n\${color 888888}Show-lyric: \${color FF0000} $msg" > "$outfile"
   echo -e "Show-lyric: $msg" > /dev/stderr
}


# Get current song position
position=$(playerctl -p $(cat "./tempfiles/player.running") position --format "At position: {{ duration(position) }}") # "
position=$(echo "$position" | awk -F'At position: ' '{print $2}')

   if [ "$timing" -gt "0" ]; then
     pos="00:$position"
     epos=$(date -u -d $pos +'%s')
     eposplus=$(echo "$(date -u -d $pos +'%s')" +$timing | bc) #"
     newpos=$(date -u -d @"$eposplus" +'%H:%M:%S')
     position=$(echo "${newpos:3}" | sed 's/^0//g')
   fi


while read -r line
do
    lyrtime=$(echo "$line" | awk '{print $1}')
    lyrtime=$(echo "${lyrtime:1:-4}" | sed 's/^0//g')
    if [ "$lyrtime" = "$position" ]; then
      rm -f "./tempfiles/first.time"
      cat "$txtfile" | tail -n+4 | grep -A2 -B2 $lyrtime | awk -F'] ' '{print "<objects>"$NF}' > "$tmpfile"
      cat "$tmpfile" | head -n1 | tail -n1 | sed "s/<objects>/$offset1$font1\${color $col1}/g" > "$outfile"
      cat "$tmpfile" | head -n2 | tail -n1 | sed "s/<objects>/$offset2$font2\${color $col2}/g" >> "$outfile"
      cat "$tmpfile" | head -n3 | tail -n1 | sed "s/<objects>/$offset3$font3\${color $col3}/g" >> "$outfile"
      cat "$tmpfile" | head -n4 | tail -n1 | sed "s/<objects>/$offset2$font2\${color $col2}/g" >> "$outfile"
      cat "$tmpfile" | head -n5 | tail -n1 | sed "s/<objects>/$offset1$font1\${color $col1}/g" >> "$outfile"
    elif ! [ "$(date -d "$lyrtime" +'%s')" -gt "$(date -d "$position" +'%s')" ]; then
      if [ -f "./tempfiles/first.time" ]; then
        cat "$txtfile" | tail -n+5 | head -n5 | awk -F'] ' '{print "<objects>"$NF}' > "$tmpfile"
        echo "" > "$outfile"
        echo "" >> "$outfile"
        cat "$tmpfile" | head -n1 | tail -n1 | sed "s/<objects>/$offset3$font3\${color $col3}/g" >> "$outfile"
        cat "$tmpfile" | head -n2 | tail -n1 | sed "s/<objects>/$offset2$font2\${color $col2}/g" >> "$outfile"
        cat "$tmpfile" | head -n3 | tail -n1 | sed "s/<objects>/$offset1$font1\${color $col1}/g" >> "$outfile"
      fi
    fi

done< <(cat "$txtfile" | tail -n+4)
