#!/bin/bash
fetch_art(){
    first_cover=""
    if [ -e ~/.conky/music/meta ]
    then
        new_cover=$(cat ~/.conky/music/meta | awk -F \' '{for(i=1;i<=NF;i++) if ($i=="mpris:artUrl") print $(i+2)}')
        if [ "$new_cover" != "$first_cover" ]
        then
            first_cover="$new_cover"
            wget -O ~/.conky/music/last_album_pic.png $new_cover
        fi
    fi
}

fetch_meta(){
    old_meta=""
    if [ "$(playerctl status)" = "Playing" ]
    then
        new_meta=$(playerctl metadata)
        if [ "$new_meta" != "$old_meta" ]
        then
            echo $new_meta > ~/.conky/music/meta
            old_meta=$new_meta
        fi
    else
        new_meta=''
        if [ -e ~/.conky/music/meta ]
        then
            rm ~/.conky/music/meta
        fi
    fi
}

running=false

while :
do
    if [ $running = false ]; then
        spotify_process_id=$(pidof spotify)
        if [[ ! -z $spotify_process_id ]]; then
            ~/.conky/music/fetch_meta.sh & meta_PID=$!
            ~/.conky/music/fetch_art.sh & art_PID=$!
            running=true
        fi
    else
        spotify_process_id=$(pidof spotify)
        if [[ -z $spotify_process_id ]]; then
            if [[ ! -z $meta_PID ]]; then
                kill $meta_PID
            fi
            if [[ ! -z $art_PID ]]; then
                kill $art_PID
            fi
            running=false
        fi
    fi
    sleep 10
done
