#!/bin/bash
# Can parse 'max_length=SOME_INTEGER' as argument 
# (example: ./now-playing max_lentgh=40)

default_max_length=45

# Function to trim the info if it exceeds 'max_length' characters
trim_info() {
    local info="$1"
    local max_length="$2"

    if [ ${#info} -gt $max_length ]; then
        local trim_length=$((max_length - 1))
        info="${info:0:$trim_length}…"
    fi

    echo "$info"
}

# Parse the command-line argument for max_length
if [[ $1 =~ max_length=([0-9]+) ]]; then
    max_length="${BASH_REMATCH[1]}"
else
    max_length=$default_max_length
fi

# Check if Spotify is playing
spotify_status=$(playerctl --player=mpd status 2>/dev/null)

if [ "$spotify_status" == "Playing" ]; then
    # Get currently playing song from Spotify
    info=$(playerctl metadata --player=mpd --format '  {{title}} • {{artist}}')
fi

trimmed_info=$(trim_info "$info" "$max_length")
echo "$trimmed_info"
