#!/usr/bin/env sh

# Description: Play random music (MP3, FLAC, M4A, WEBM, WMA) from current dir.
#
# Dependencies: mocp (or custom)
#
# Note: You may want to set GUIPLAYER.
#
# Shell: POSIX compliant
# Author: Arun Prakash Jana

GUIPLAYER="${GUIPLAYER:-""}"
NUMTRACKS="${NUMTRACKS:-100}"

if [ -n "$GUIPLAYER" ]; then
    find . -type f \( -iname "*.mp3" -o -iname "*.flac" -o -iname "*.m4a" -o -iname "*.webm" -o -iname "*.wma" \) | shuf -n "$NUMTRACKS" | xargs -d "\n" "$GUIPLAYER" > /dev/null 2>&1 &

    # detach the player
    sleep 1
elif type mocp >/dev/null 2>&1; then
    cmd=$(pgrep -x mocp 2>/dev/null)
    ret=$cmd

    if [ -z "$ret" ]; then
        # start MOC server
        mocp -S
        mocp -o shuffle
    else
        # mocp running, check if it's playing
        state=$(mocp -i | grep "State:" | cut -d' ' -f2)
        if [ "$state" = 'PLAY' ]; then
            # add up to 100 random audio files
            find . -type f \( -iname "*.mp3" -o -iname "*.flac" -o -iname "*.m4a" -o -iname "*.webm" -o -iname "*.wma" \) | head -n "$NUMTRACKS" | xargs -d "\n" mocp -a
            exit
        fi
    fi

    # clear MOC playlist
    mocp -c
    mocp -o shuffle

    # add up to 100 random audio files
    find . -type f \( -iname "*.mp3" -o -iname "*.flac" -o -iname "*.m4a" -o -iname "*.webm" -o -iname "*.wma" \) | head -n "$NUMTRACKS" | xargs -d "\n" mocp -a

    # start playing
    mocp -p
else
    printf "moc missing"
    read -r _
fi
