#!/bin/bash

# Jukebox.sh - a simple bash script to randomly play mp3s in a directory using a 
# specified player. v0.2 (C) 2004-2005 Duc Le
# 060925 - Changed default player to mpg123 and added windows cygwin support

# Defaults
reps=10
if [[ $OSTYPE == "linux-gnu" ]] 
then
  player="mpg123"

  while getopts ":v:p:r:" Option
  do
    case $Option in
        # Volume control assumes ALSA!
        v ) amixer sset PCM,0 $OPTARG% unmute > /dev/null ;;
        p ) player=$OPTARG ;;
        * ) ;;
    esac
  done
  shift $(($OPTIND -1))

elif [[ $OSTYPE == "cygwin" ]] 
then
  player="CLAmp \PLCLEAR \PLADD"

else
  echo Sorry, your OS is not supported
fi

if [ "$*" != "" ]
    then
    reps=$*
fi

num=0
# Finds all mp3s in directory and sub-directories
for dir in `find -type d -follow`
  do
  for mp3 in "$dir"/*.[Mm][Pp]3
    do
    if [ "$mp3" != "$dir/*.[Mm][Pp]3" ]
	then
	file[$num]=$mp3
	let "num += 1"
    fi
  done
done

# Reseeds random generator
SEED=$(head -n 1 /dev/urandom | od -N 1 | awk '{ print $2 }')
RANDOM=$SEED
filelist=""

# Plays $reps random mp3s
for ((n=1; n <= reps; n++))
  do
  if [ "$num" != 0 ]
    then
    indx=$((RANDOM % num)) 
    if [[ $OSTYPE == "linux-gnu" ]] 
    then
      ${player} "${file[$indx]}"
    elif [[ $OSTYPE == "cygwin" ]] 
    then
      #filelist="${filelist} ${file[$indx]}"
      ${player} "${file[$indx]}" \PLAY
    fi
  fi
done
  
#if [[ $OSTYPE == "cygwin" ]]
#  exec CLAmp \CLCLEAR \PLADD $filelist \PLAY
#fi
