#!/usr/bin/perl
#mp3burn 0.02 10/28/00
#Copyright 2000 Ryan Richter <bobort@bigfoot.com>
#With help from Dan Lark <dlark@spinn.net>
#You may fold, spindle, and mutilate this software under the terms of the GPL

eval "use MPEG::MP3Info";
if ($@) {
	$no_mp3info = 1;
}
use Getopt::Std;
use File::Basename;


getopts('c:dt:o:', \%opts);

$dummy="-dummy " if ($opts{'d'});
if (length($opts{'t'}) > 1) {
	$tmpdir=$opts{'t'}."/";
	die "Cannot write to temp. dir -> $tmpdir" unless  ( -d $tmpdir &&  -w $tmpdir);
}
if (length($opts{'c'}) > 1) {
	die "Time check not available without MPEG::MP3Info module" if $no_mp3info;
	die "Time check needs to be in the form of MMM:SS" unless ($opts{'c'} =~ /\d{0,3}\:\d{2}$/);
	($min,$sec)=split(/\:/,$opts{'c'});
}


#Below is what the README told you to change.
#$cdrecord_opts = "-v dev=1,0 speed=4 -pad -swab -audio";

if (-r "$ENV{'HOME'}/.mp3burnrc") {		#process ~/.mp3burnrc
	open(RC, "$ENV{'HOME'}/.mp3burnrc");
	$oldRS = $/;
	undef $/;
	$rc = <RC>;
	close(RC);
	unless(defined eval $rc) {
		die "Error in .mp3burnrc:\n$@";
	}
	$/ = $oldRS;
}
$cdrecord_opts = $opts{'o'} if $opts{'o'};	# -o overrides .mp3burnrc
if ($cdrecord_opts eq '') {
	die "Need to specify cdrecord options through -o or .mp3burnrc\n" .
		"Usage:  mp3burn [-c MMM:SS] [-d] [-t tmpdir] [-o cdrecord_opts] [mp3 files]\n";
}
$cdrecord_opts .= "$dummy -pad -audio";

if ($#ARGV < 0) {				#give usage if no args
	die "Usage:  mp3burn [-c MMM:SS] [-d] [-t tmpdir] [-o cdrecord_opts] [mp3 files]\n";
}

for($i = 0; $i <= $#ARGV; $i++) {		
	die "$ARGV[$i] does not exist" unless (-f $ARGV[$i]); #Check to see if file exists
	$fifo[$i] = $tmpdir . basename $ARGV[$i];	#set the names of the fifos
	$fifo[$i] =~ s/mp3$/cdr/i;		#foo.mp3 -> foo.cdr
	if ($sec) {	
		if (-l $ARGV[$i]) {		#mp3info doesn't work on symlinks
			$file = readlink $ARGV[$i];
		} else {
			$file = $ARGV[$i];
		}
		$info = get_mp3info $file; #Let's get the mp3's time
		$totsecs += ($info->{MM}*60) + $info->{SS} + 4; #Calculate total time adding a fudge factor of 4 secs
	}
	system "mkfifo", $fifo[$i];	#Make our fifos (optionally to the tempdir)
	if (fork() == 0){			#start decoder processes
		close(STDOUT);
		open(STDOUT, ">$fifo[$i]");	#this to avoid using the shell
		exec("mpg123", "--rate", "44100", "--stereo", "-s", $ARGV[$i]);
		die "Failed to exec mpg123: $!";
	}
}

$totmin=int $totsecs/60;
$totsec=$totsecs % 60;
if (($totsecs > (($min*60)+$sec)) && $sec) {
	print "The max time allocated was [$min:$sec].\n";
	print "The total time came to [$totmin:$totsec].\n";
	print "Do you wish to continue? (Y/N) ";
	while (1) {
		$key=uc(getc);
		if ($key eq 'N') {
			unlink @fifo;
			exit 1;
		}
		last if ($key eq 'Y');
	}
}
if ($sec){
	print "Total time is [$totmin:$totsec]\n";
	sleep 3;
}
 
#now we burn

system "cdrecord", split(/\s+/, $cdrecord_opts), @fifo;


#clean up
unlink @fifo;
