#!/bin/sh
#
# Play MP3 files based on remote control input
#
# $Id: mplay,v 1.13 2002/04/07 10:53:47 dds Exp $
# 
# (C) Copyright 2000-2002 Diomidis Spinellis
# 
# Permission to use, copy, and distribute this software and its
# documentation for any purpose and without fee is hereby granted,
# provided that the above copyright notice appear in all copies and that
# both that copyright notice and this permission notice appear in
# supporting documentation.
# 
# THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
# MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
#

# Master playlist file
PLAYLIST=/vol/db/playlist

# Collection directory
PLAYLIST=/vol/db/collections

# Redirect output to the log file
exec 2>/var/log/mplay.log 1>/var/log/mplay.log

date
echo mplay starting

./irw /dev/lircd |
while read code rep key rem
do
	if [ $rep != 00 ] ; then continue ; fi
	case $key in
	play)
		# Continue if paused
		if [ .$paused  = .1 -a .$idx = . ]
		then
			kill -CONT $PID
			paused=''
			continue
		fi
		# Stop if playing
		if [ .$PID != . ]
		then 
			kill $PID
			PID=''
		fi
		echo
		audioplay laser.wav

		# Default index
		if [ .$idx = . ] ; then idx=1 ; fi

		# Create playlist
		if [ $idx -lt 100 ]
		then
			# Shuffle from a collection
			COL=`grep -l "^CN $idx\$" $COLLECTIONS/*`
			awk '/^[0-9]/ {
				print "/^# " $1 "\$/,/^\$/p"
			}' >sedfile <$COL
			# Print 3 and 4 letter collections
			# First isolate them by a newline, then print them
			sed -e '/# [0-9][0-9][0-9]$/s/^/\
/
			/# [0-9][0-9][0-9][0-9]$/s/^/\
/' 				$PLAYLIST |
			sed -f sedfile -n |
			shuffle -f -
		else
			# Start from a given point
			sed -n "/^# $idx\$/,\$p" $PLAYLIST
		fi >playlist
		if [ -s playlist ]
		then
			mpg123 -@ playlist &
			PID=$!
		else
			# Error, no file could be created
			audioplay boingiggig.wav
		fi
		idx=''
		;;
	[0-9])
		# Continue if paused
		if [ .$paused  = .1 ]
		then
			kill -CONT $PID
			paused=''
		fi
		if [ .$PID != . ]
		then 
			echo Terminating mpg
			kill $PID
			PID=''
		fi
		echo -n $key
		audioplay Beep.wav
		idx="$idx$key"
		;;
	stop)
		echo stop
		kill $PID
		PID=''
		;;
	prev)
		echo prev
		kill -USR1 $PID
		;;
	next)
		echo next
		kill -USR2 $PID
		;;
	pause)
		echo pause
		kill -STOP $PID
		paused=1
		;;
	esac
done
