#! /usr/bin/perl -w

#--------------------------------------------------------------------------
# Prepare the files for a CDDA burn from a playlist and MP3 or OGG files
#--------------------------------------------------------------------------

use strict;
use Getopt::Std;


our ($opt_c, $opt_s);
my ($srcListFull, $srcListDir, $srcListBase, $tocPath, $command);
my $usage=<<EOF;
$0 v1.0.1 - Prepare files for a CDDA from a playlist and MP3 or OGG files

usage:
  $0 [-c "artist"] [-s "cdtitle"] file
  $0 --help

  -c artist   For the label, artist name to use instead of what's in track 1
  -s cdtitle  For the label, CD title to use instead of what's in track 1
  file        m3u playlist file
  --help      Show command help
EOF


#--------------------------------------------------------------------------
# It all starts here

# Detect if no params given.
if(@ARGV == 0 || $ARGV[0] eq "--help")
{ die "$usage\n"; }

# Parse arguments.
getopts("c:s:");

$srcListFull = shift;

if(!defined $srcListFull) {
	print "No playlist specified!\n";
	die "$usage\n";
}

$srcListFull =~ m|(.*)/([^.]*).*|;
$srcListDir = $1;
$srcListBase = $2;

$tocPath = "$srcListBase.toc";

open (SRC_FILE, "$srcListFull") || die "Can't open $srcListFull\n";
open (TOC_FILE, ">$tocPath") || die "Can't open $tocPath\n";

print TOC_FILE "CD_DA\n";

while (<SRC_FILE>) {
	chop;

	/^([^#].*)$/ && do {
		print TOC_FILE "\nTRACK AUDIO\nSTART 0:2:0\n";

		my $srcSongPath = $1;
		$srcSongPath =~ m|(.*)/([^.]*)\.(.*)|;
		my $srcSongDir = $1;
		my $destSongPath = "$2.wav";
		my $srcSongExt = $3;

		$srcSongPath =~ m|^[^/]| && do
		{ $srcSongPath = $srcListDir . "/" . $srcSongPath; };

		SWITCH: {
			$srcSongExt =~ /mp3/ && do {
				system("mpg123 -w $destSongPath $srcSongPath");
				last SWITCH;
			};
			$srcSongExt =~ /ogg/ && do {
				system("oggdec -o $destSongPath $srcSongPath");
				last SWITCH;
			};
		}

		print TOC_FILE "FILE \"$destSongPath\" 0\n";
	};
}

close TOC_FILE;
close SRC_FILE;


$command = "mulabel ";
$command .= ($opt_c ? qq/-c "$opt_c" / : "");
$command .= ($opt_s ? qq/-s "$opt_s" / : "");
$command .= $srcListFull;
system($command);
__END__

toc files look like below
(more info can be found in the man page for cdrdao)

CD_DA

TRACK AUDIO
FILE "PinkFloyd-ShineOnYouCrazyDiamond.wav" 0

TRACK AUDIO
FILE "PinkFloyd-WelcomeToTheMachine.wav" 0

TRACK AUDIO
START 0:2:0
FILE "PinkFloyd-HaveACigar.wav" 0

TRACK AUDIO
START 0:2:0
FILE "PinkFloyd-WishYouWereHere.wav" 0

TRACK AUDIO
FILE "PinkFloyd-ShineOnYouCrazyDiamondPart2.wav" 0
