#!/bin/sh

# subsonic
alias subsonic-cli="\subsonic-cli -c $HOME/.subsonic-cli.conf"

subsonic-play() {
    # $1 songId
    for song in $@
    do
        echo $song > /tmp/.playing
        subsonic-cli stream -p id $song \
            | mpv --loop=no - || exit 0
    done
}

subsonic-random() {
    while true;
    do
        echo "Fetching moar dataaa.."
        subsonic-play $(subsonic-cli getRandomSongs \
            | jq -r '.randomSongs[][].id')
    done
}

subsonic-favorites() {
    while true;
    do
        echo "Fetching moar dataaa.."
        subsonic-play $(subsonic-cli getStarred \
            | jq -r '.starred[][].id' \
            | sort -r)
    done
}

subsonic-search() {
    {
    echo "|ALBUMID|ID|ALBUM|ARTIST|TITLE|GENRE|"
    printf "|%s|%s|%s|%s|%s|%s|\n" "--------------------------------"\
                                   "--------------------------------"\
                          "--------" "--------" "--------" "--------"
    subsonic-cli search3 \
      -p songcount 200 \
      -p query "$@" \
      | jq -r '.searchResult3[][]|select(.contentType!=null)|[.albumId,.id,.album,.title,.artist,.genre]' \
      | tr -d '", ' \
      | awk '/^\[/ { S++ }       \
             /^\]/ { S-- }       \
              S==0 { NR=0  }     \
             NR==2 { AID=$0 }     \
             NR==3 { ID=$0 }     \
             NR==4 { ALBUM=$0 }  \
             NR==5 { TITLE=$0 }  \
             NR==6 { ARTIST=$0 } \
             NR==7 { GENRE=$0 }  \
             NR==0 { printf("|%s|%s|%s|%s|%s|%s|\n", AID, ID, ALBUM, ARTIST, TITLE, GENRE) }'
      } | column -s'|' -t
}

subsonic-star() {
    [ -f /tmp/.playing ] \
        && subsonic-cli star -p id $(cat /tmp/.playing | tail -1) \
        || echo bruh.
}

subsonic-unstar() {
    [ -f /tmp/.playing ] \
        && subsonic-cli unstar -p id $(cat /tmp/.playing | tail -1) \
        || echo bruh.
}

subsonic-download() {
    # $1 albumId
    NAME=$(subsonic-cli getAlbum -p id $1 \
        | jq -r '.album.artist,.album.name' | xargs | tr ' ' '-')
    printf "Downloading to %s/subsonic-download/%s.zip\n" "$HOME" "$NAME"
    mkdir -p "$HOME/subsonic-download"
    subsonic-cli download -p id $1 | pv > "$HOME/subsonic-download/$NAME.zip"
}

if [ -z $1 ]
then
    cat <<"EOF"
    usage: subsonic <command> <args>

    play <song id>          - play song with id
    download <album id>     - download album with id
    [un]star                - [un]star currently playing song
    search <term>           - show song/album for term
    favorites               - play starred songs
    random                  - play random songs

EOF
else
    subsonic-$1 $2
fi


