#!/bin/bash
# shuber, 2007-11-17
#
# Changelog:
#   * 2010-09-19  add --remove option for podcast files
#                 add destination directories
#                 add -v|--verbose options
#   * 2008-11-08  also get *.MP3 files
#   * 2008-11-12  introduce a $player variable
#                 delete $playlist file after playing
#                 add a -quiet argument
#   * 2009-02-14  spell fixing
#   * 2010-09-7   change playlist file
#                 use mplayers capabilities for --random and --repeat


playlist=.playlist.tmp
player=/usr/bin/mplayer

optRandom=
optRepeat=
optRecursive=0
optRemove=0
optQuiet=
optVerbose=0


function showHelp
{
	echo "Plays mp3 files in all subdirectories."
	echo "Usage: ./mp-play.sh [-h|--help] [-R|--random] [-r|--repeat] [-a|-recursive] [--remove] [-q|--quiet] [-v|--verbose] [DESTINATION]"
}

# List of destinations
dest=

#Parse the arguments
while [ $# -gt 0 ]
do
	case "$1" in
		-h|--help)
		showHelp
		exit 0
		;;

		-R|--random)
		optRandom="-shuffle"
		;;

		-r|--repeat)
		optRepeat="-loop 0"
		;;

		-a|--recursive)
		optRecursive=1
		;;

		-v|--verbose)
		optVerbose=1
		;;

		-q|--quiet)
		optQuiet="-quiet"
		;;

		--remove)
		optRemove=1
		;;

		*)
		dest="${dest} $1"
		;;
	esac
	shift
done



if [ "$optRecursive" == "1" ]; then
	maxlevel=9999
else
	maxlevel=1
fi
	

# Create playlist
find $dest -maxdepth $maxlevel -type f \
	-iname "*.mp3" -or -iname "*.avi" -or -iname "*.flv" \
	| sort > $playlist


cntfiles=`wc -l $playlist | cut -d " " -f 1`

#No files found...
if [ "$cntfiles" == "0" ]
then
	echo "No files found."
	exit 1
fi



echo "Playing $cntfiles files..."
echo ""

# Print playlist, if we ask for removing files later
if [ "$optRemove" == "1" -o "$optVerbose" == "1" ]; then
	cat $playlist
fi


# Play it
$player $optQuiet $optRandom $optRepeat -playlist $playlist



# Remove the files in the playlist
if [ "$optRemove" == "1" ]; then
	echo ""
	echo -n "Removing played files? (y/a/N) "
	read isdel
	if [ x"y" == x"$isdel" ]
	then
		rm -v `cat $playlist`
	elif [ x"a" == x"$isdel" ]
	then
		rm -v -i `cat $playlist`
	fi
fi

#Remove the playlist itself
rm -f $playlist

