#!/bin/bash

MINBASE=/usr/local/minerva
LOGFILE=/var/log/minerva/manifest/playlist
DEVICE=$1

MP3BASE=/net/media/mp3
MP3BASE=/net/genre/pop

# pick a random file in this directory
IFS=$'\n'
CURRENTDIR=$MP3BASE
FOUNDFILE=0

while [ $FOUNDFILE -eq 0 ]; do
   DIRLIST=( $(ls "$CURRENTDIR") )

   if [ ${#DIRLIST[@]} -eq 0 ]; then
      CURRENTDIR=$MP3BASE
   else
      SELECTION=$RANDOM
      let "SELECTION %= ${#DIRLIST[@]}"

      FILENAME=$CURRENTDIR/${DIRLIST[$SELECTION]}
      if [ -f $FILENAME ]; then
        FILETYPE=`file $FILENAME`
        if [[ "$FILETYPE" =~ 'MP3 encoding' || "$FILETYPE" =~ 'OGG' || "$FILETYPE" =~ 'MPEG' ]]; then 
           date +"%F %H:%M $FILENAME" >> $LOGFILE
           $MINBASE/bin/mp3player $DEVICE play $FILENAME &>/dev/null
           FOUNDFILE=1
        else
          CURRENTDIR=$MP3BASE
        fi
      else
        CURRENTDIR=$FILENAME
      fi
   fi

done

