#! /bin/zsh -feu

zmodload zsh/regex
. /usr/share/mmc-shell/mmc-functions.sh
colors

function usage()
{
    setopt POSIX_ARGZERO
    cat <<EOF
usage: ${0##*/} [+-va} [--] [nr] files...
-v  verbose
-g  use gstreamer (rather than mplayer)
-p  pulse
-a  alsa
EOF
}

function play_mplayer()
{
    mplayer -vo null -ao pulse $mplayer_args "$1" </dev/null
}

function is_number()
{
    # expr match $1  '^[[:digit:]]\+$' &> /dev/null
    readonly NUMBER_RX='^[[:digit:]]+$'
    [[ $1 -regex-match $NUMBER_RX ]]
}

function play_file ()
{
    # cecho  red "play $1:"
    case $(realpath $1) in
        *.mpg)
        # mpg123 -b 10000 "$1" ;;
            info $1
            $MPG123 "$1"
            ;;
        *.mp2)
            info $1
            $MPG123  "$1" ;;

         *.xmms.mp3)
            echo xmms  --play ${1}
            ;;
        *.mp3)
            info "$1"
        #    echo `color red`  `color bd` $1 `color off`

       # mpg321 skips when over Net!
       # --buffer 10000
       # problems w/ hi bit-rates!
       # mpg321 --aggressive -o alsa09 -q -b 10000  "$1"

       # -b 10000    ... fails silently!
       # fixme: this is oss, not ALSA!
            $MPG123  "$1"
            ;;

        *.ogg)
            info "$1"
            if which ogg123; then
                if [[ $pulse = y ]]; then
                    ogg123 -d pulse --quiet  "$1"
                else
                    ogg123 --quiet  "$1"
                fi
            else
                gst123 --novideo --quiet $1
            fi
            ;;
        *.flv | *.mp4 | *.m4a | *.wma | *.webm | *.ape | *.mkv )
            info "$1"
            #
            if which mplayer > /dev/null && [[ $use_gst == 'no' ]] ; then
                play_mplayer $1
            else
                if [[ $verbose = y ]]
                then
                    DISPLAY= gst123 --novideo  "$1"
                else
                    DISPLAY= gst123 --novideo --quiet "$1"
                fi
            fi
            ;;

        *.flac)
            info "$1"
            if which mplayer > /dev/null ; then
                play_mplayer $1
            else
                # gst123 --quiet $1 &> /dev/null </dev/null
                # gst123 insists on having the console (being in foregroung).
                flac --silent --decode --stdout $1 |\
                    if [[ $pulse = y ]]; then
                        paplay
                    else
                        aplay  -q  -
                    fi
            fi
            ;;
        *tif|*png|*txt|*jpg)
            # skip those
            ;;
        *)
            # especially when a symlink to mp3:
            $MPG123 "$1"
            # play_mplayer $1
            ;;
    esac
}

play_one()
{
    local song=$1

    if [[ $START -gt 1 ]];
    then
        ((START=START - 1))
        # echo $START
    else

        if [[ -d "$song" ]]
        then
            info $song
            (cd "$song"
             play_dir
            )
        else
            play_file "$song"
        fi
    fi
}

play_dir()
{
    # local
    readonly songs=( $( ls -v -Q --quoting-style=shell)) # (*(l))

    local song
    foreach song ( *(n) ) # $songs
    {
        # unsetopt SH_WORD_SPLIT

        # We must return to use commonly accepted syntax:
        # IFS="${old_ifs}"

        play_one $song
    }
}

alsa=n
use_gst=no

# (positive) defaults:
pulse=y
MPG123=(mpg123-pulse --gapless ${playdsp+-a $playdsp} --aggressive -q --title)
mplayer_args=(-ao pulse)

START=0
verbose=n
mplayer_args=(-ao pulse,alsa)

while getopts :aghpqv OPT; do
    case $OPT in
        g)
            use_gst=yes
            MPG123=(gst123 --novideo --quiet)
            ;;
        v|+v)
            verbose=y
            set -x
            ;;
        a|+a)
            alsa=y
            MPG123=(mpg123-alsa --gapless ${playdsp+-a $playdsp} --aggressive -q)
            ;;
        p)
            pulse=y
            MPG123=(mpg123-pulse --gapless ${playdsp+-a $playdsp} --aggressive -q)
            mplayer_args=(-ao pulse)
            ;;
        q)
            MPG123+=(--no-control --fifo /run/tmp/play-fifo )
            ;;
        h)
            usage
            exit 0
            ;;
        *)
            usage
            exit 2
    esac
done
shift OPTIND-1
OPTIND=1

if [[ $# -gt 0 ]] && [[ ! -a $1 ]] && is_number $1; then
    START=$1
    shift
fi


if [[ $verbose = y ]]; then
    mplayer_args+=(-msglevel all=9)
else
    mplayer_args+=(-really-quiet)
fi


# decide:
if [[ "$pulse$alsa" = "nn" ]]; then
   # try more:
   if [[ -n ${PULSE_SERVER-} ]] || pulseaudio --check; then
       # this suddenly requires staying in fg! and "space" to pause.
       MPG123=(mpg123-pulse --no-control --gapless ${playdsp+-a $playdsp} --aggressive -q)
   elif which mpg321 > /dev/null; then
       # -b 10000
       MPG123=(mpg321 --aggressive -q)
   fi
fi

if [[ $# -gt 0 ]]; then
    for file in "$@"; do
        play_one $file
    done
else
    play_dir
fi
