#!/usr/local/bin/perl
#
#
# miffmixr v.01  (mxauto)
#
# part of the wweb based miffmixr product
# free for noncommercial use
#
# miff@9mm.com
#
# werd.
#
# this is the daemon that creates the "master list"
#  file for the front end to read.  needs at least
#  1 relevant directory list /usr/local/miffmixr/conf/basedirs
#  

my $basedirs = "/usr/local/miffmixr/conf/basedirs";
my $masterfile = "/usr/local/miffmixr/conf/masterfile";

#first get our working dirs:
open BASEDIRS, $basedirs || die ("NO BASE FILE! /usr/local/miffmixr/conf/basedirs needs to have at lest 1 dir in it!");
open MASTERFILE, ">$masterfile" || die ("problems opening masterfile $masterfile\n");

while ($basedir = <BASEDIRS>) {
	#iterative search for all dirs in here.
	#write out all the dirs w/mp3s in them as "albums"
	# or panels for the jukebox.  put the mp3s in each
	#panel.
	chomp $basedir;
	
	# format will be:
	# 1:PAGE:/vault/miff/mp3/Ozzy   <-- sequence:PAGE "folder" designation:page title
	# 1:1:/vault/miff/mp3/Ozzy/crazytrain.mp3  <-- song
	# 1:2:/vault/miff/mp3/Ozzy/mrcrowley.mp3  <-- song

	# an initial contents array:
	opendir TMPDIR, $basedir or die "bad bad abd \n"; 
	#my @contents = readdir TMPDIR;
	my @contents = grep !/^\.\.?$/, readdir TMPDIR;
	closedir TMPDIR;
	my @thesedirs;
	my @nextdirs;

	my $d;  #dir var
	my $dthing;  #dir content
	my $lastpage;  #page var
	my $pagecount;
	my $songcount;

	# first put dirs from contents into thesedirs:
	foreach $d (@contents) {
		chomp $d;
		$d = $basedir . "/" . $d;
		if (-d "$d") {  
			#is it a dir?
			push @thesedirs, $d;
		}
		#note:  we would normally do an else here and
		# if it were an mp3 put it in master but really
		#  since this is the base dir we dont want that.
		#  do we?
	} 


	while (@thesedirs) {	
		#this is the master iterative loop!
		# thesedirs will get filled in with @nextdirs after empty
		foreach $d (@thesedirs) {
			$songcount = 0;  #clear the song count
			# READ THE DIR!!
			opendir TMPDIR, $d or die "bad bad double bad \n"; 
			my @dstuff = grep !/^\.\.?$/, readdir TMPDIR;
			closedir TMPDIR;
			foreach $dthing (@dstuff) {
				if ($dthing eq ".directory") {
					next;
				}
				$dthing = $d . "/" . $dthing;
				if (-d $dthing) {
					#its another dir!  put it in @nextdirs
					push @nextdirs, $dthing;
				} elsif ($dthing =~ "mp3") {
					#its a song!
					# check if theres already a page desig.
					if ($lastpage eq $d) {
						#we cool on the page
					} else {
						# this is a new page
						$pagecount++;
						print MASTERFILE "$pagecount:PAGE:$d\n";
						$lastpage = $d;
					}
					#put it in the file!
					$songcount++;
					print MASTERFILE "$pagecount:$songcount:$dthing\n";
				}
			}
		}
		# done looping thru thesedirs, replace with new array:
		@thesedirs = @nextdirs;
		@nextdirs = ();
	}


}
close MASTERFILE;
close BASEDIRS;



