#!/usr/bin/perl

print "--Updating Play Lists--.\n";

$rootDir = "$ARGV[0]";

$playlistsDir = "$rootDir/Library/QuickTimeStreaming/Playlists";


opendir PLAYLISTDIR, $playlistsDir or die "Couldn\'t open $playlistsDir";
## skip '.' files and non-directories
my @dirList = map "$_", grep {
	not /^\.\.?\z/s and
	-d  "$playlistsDir/$_"  # XXX: dirseps
} readdir PLAYLISTDIR; 
closedir PLAYLISTDIR or die "Couldn\'t close $playlistsDir";

PROCESSDIR: foreach $dir (@dirList)
{

	if ( open(PLBCFGFILE, "$playlistsDir/$dir/$dir.config") )
	{


		@buf = ();
		my $isAPlbFile = 0;

		while ($line = <PLBCFGFILE>)
		{
			push @buf, $line;
			
			if ( $line =~ /^playlist_file\s(.*)/ )
				{ $isAPlbFile = 1; }
		}
		close (PLBCFGFILE);
		
		## skip it if it doesn't appear to be a valid file
		if ($isAPlbFile != 1)
			{print "Skipping play list: $dir\n"}
		next PROCESSDIR if ($isAPlbFile != 1);

		if ( open(NEW_PLBCFGFILE, ">$playlistsDir/$dir/$dir.config.TEMP") )
		{		
			print "Updating play list: $dir\n";
		
			PROCESSLINE: foreach $line (@buf)
			{
				next PROCESSLINE if ( $line =~ /(^destination_base_port)/ );
				
				#if ( $line =~ /(^playlist_file)\s(.*)/ ||
				#	 $line =~ /(^sdp_reference_movie)\s(.*)/ ||
				#	 $line =~ /(^destination_sdp_file)\s(.*)/ ) 
				#{
				#	# quote the path
				#	$line = "$1 \"$2\"\n";
				#}
				
				#if ( $line =~ /(^sdp_file)\s(.*)/ )
				#{
				#	# quote it, make full path, and change to name Playlist name 
				#	$line = "$1 \"$playlistsDir/$dir/$dir.sdp\"\n";
				#}

		
				print NEW_PLBCFGFILE $line
			} ## foreach $line (@buf)
			
			#add new 4.0 lines
			print NEW_PLBCFGFILE "#broadcast_name \"$dir\"\n";
			print NEW_PLBCFGFILE "log_file \"$playlistsDir/$dir/$dir.log\"\n";
			print NEW_PLBCFGFILE "pid_file \"$playlistsDir/$dir/$dir.pid\"\n";
			
			close (NEW_PLBCFGFILE)
		}
		
		rename "$playlistsDir/$dir/$dir.config.TEMP", "$playlistsDir/$dir/$dir.config"
	
	}

} ##foreach $dir (@dirList)

print "--Playlist Update Complete--\n";