#!/bin/sh
#
# Copyleft 2005 Grifter, GPL and all that.
#
#  This is a script to play a random playlist, in which it won't repeat
#  the same song twice in a cycle, the cycle being the sum total of the files.
#  Meant for midis, since there is no adequate console midiplayer with shuffle,
#  but could work with anything really.
#
#  Builds an array of filenames in a dir, and starts checking the played songs
#  on the second run.
#  
#  Depends on pmidi (ALSA)
#
# v1.3

if [ -z $1 ]; then
	echo "You must specify a directory to work in."
	exit 1
	elif [ ! -d $1 ]; then
		echo "You must specify a DIRECTORY to work in."
		exit 1
fi

LIST=`ls -1 $1 | grep -i .mid`
LIST2=`echo $LIST | sed 's/\ /\n\|\ /g' `
ARRAY=($LIST)
num_array=${#ARRAY[*]}
COUNTER=0

until [ $COUNTER = $num_array ]; do

	CURRENT_SONG="${ARRAY[$((RANDOM%num_array))]}"
	if [ ! -z "$PLAYED_SONGS" ]; then
		CHECKLIST=`echo "$PLAYED_SONGS" | grep "$CURRENT_SONG"`
		while [ ! -z "$CHECKLIST" ]; do
			CURRENT_SONG="${ARRAY[$((RANDOM%num_array))]}"
			CHECKLIST=`echo "$PLAYED_SONGS" | grep "$CURRENT_SONG"`
		done
	fi

	clear

	LIST3=`echo $PLAYED_SONGS | sed 's/\ /\n\| /g'`
	CURRENT_TRACK=$((COUNTER+1))

	echo -e "\033[1;34m,-\033[1;31mPLAYLIST\033[1;34m--------------------------------------------------"
	echo -e "\033[1;34m|"
	echo -e "\033[1;34m|-----------------------------------------------------------"
	echo -e "\033[1;34m| \033[1;31mPlaylist is \033[1;33m$num_array \033[1;31mtracks long"
	echo -e "\033[1;34m|-----------------------------------------------------------"
	echo -e "\033[1;31m| $LIST2"
	echo -e "\033[1;34m|-----------------------------------------------------------"
	echo -e "\033[1;34m| \033[1;31mCurrently Playing \033[1;33m$CURRENT_SONG  \033[1;31m-- $CURRENT_TRACK/$num_array"
	echo -e "\033[1;34m|-----------------------------------------------------------"
	echo -e "\033[1;34m| \033[1;31mAlready Played"
	echo -e "\033[1;31m| $LIST3"
	echo -e "\033[1;34m\`-----------------------------------------------------------"

	pmidi -p 65:1 "${1}/${CURRENT_SONG}"

	PLAYED_SONGS="$PLAYED_SONGS $CURRENT_SONG "

	let COUNTER+=1
done

