#!/usr/local/bin/perl
#
#
# miffmixr v.01  (miffmixrd)
#
# part of the wweb based miffmixr product
# free for noncommercial use
#
# miff@9mm.com
#
# werd.
#
# miffmixrd:
# this is the daemon that sits and reads the 
#  playlist, deleting entries as they get read:

my $playlist = "/usr/local/miffmixr/playlist/list.txt";
my $newlist = "/usr/local/miffmixr/playlist/list.new";
my $nowplaying = "/usr/local/miffmixr/playlist/nowplaying";
my $mpg123 = "/usr/local/bin/mpg123";

# this should get launched into the bg (kill -9 to stop)
# its just an endless loop:

while (1) {
	open PLAYLIST, "$playlist";
	die "NO PLAYLIST" unless PLAYLIST;
	open NEWLIST, ">$newlist";

	my $counter = 0;
	my $line;
	my $playme;

	#read top line from playlist then rm it!
	# (write remains to new list and mv)
	while ($line = <PLAYLIST>) {
		$counter++;
		if  ($counter == 1) {
			#play this song!
			$playme = $line;
		} else {
			#write to new file
			print NEWLIST $line;
		}
	}
	close PLAYLIST;
	close NEWLIST;
	if ($counter > 0) {
		#we got something to play:
		system("mv $newlist $playlist");
		system("chmod 666 $playlist");
		# do a "currently playing":
		system("echo \"$playme\" > $nowplaying");
		# if playme has spaces in it, we gotta fix that
		# im afraid:
		if ($playme =~ " ") {
			$playme =~ s/ /\\ /g;
		}
		if ($playme =~ ",") {
			$playme =~ s/,/\\,/g;
		}
		if ($playme =~ "&") {
			$playme =~ s/&/\\&/g;
		}
		if ($playme =~ '\(') {
			$playme =~ s/\(/\\\(/g;
		}
		if ($playme =~ '\)') {
			$playme =~ s/\)/\\\)/g;
		}
		if ($playme =~ "'") {
			$playme =~ s/'/\\'/g;
		}
		system("$mpg123 $playme");
		#should chill till song is done...
	} else {
		# wait 15 seconds and try again
		sleep 15;
	}


}
