#!/bin/bash
#
# burnmp3cue version 0.1 (c) Tillmann Steinbrecher <mail@tillmann-steinbrecher.de>
# May be distributed according to the GNU GPL, version 2
#
# This script is part of burnscripts and is called by "burnaudio".
# Don't call it directly, unless you know what you're doing.
#
# This script is for conveniently burning mp3+cue combinations from
# the command line. It will temporarily convert the MP3(s) referenced
# from the .cue file to .wav so that they can be burned from cdrdao,
# and will burn them to CD.
#
# Requires: mpg123 (most likely included with your Linux distribution)
# cueconvert from cuetools, see http://freshmeat.net/projects/cuetools/
#
#
# Edit the lines below for configuration

# the place to store temporary .wav files
wavetemp=/tmp

# write speed - set to something else than $2 to override commandline (not recommended)
speed=$2

# device to use for writing - set to something else than $1 to override commandline (not recommended)
device=$1

# additional option
#option=--simulate

###############################################################
# no changes necessary below, unless you know what you're doing

if [ -z $3 ] ; then
    echo
    echo "Usage: burnmp3cue <device> <speed> filename.cue"
    echo "Example: burnmp3cue 0,0,0 24 00-test_-_this_is_a_test.cue"
    echo "This script is typically called by burnmp3, and not used standalone."
    echo
    exit
fi

if [ ! -f $3 ] ; then
    echo
    echo "File $3 not found."
    echo
    exit
fi

convert=`awk '/FILE / { print $2 }' <$3 | awk -F \" '{print $2}' | uniq`

tocfile=$wavetemp/$3.toc

cueconvert -t cue -f $3 -f $tocfile

for i in $convert ; do
    echo "Processing $i..."
    
    # maybe it's mixed case in the .cue, but lowercase on hd
    
    if [ ! -f $i ] ; then
	i=`echo $i | tr '[:upper:]' '[:lower:]'`
	if [ -f $i ] ; then
	    echo "Using lowercase filename instead of mixed case"
	else
	    echo "Error - file not found"
	    exit
	fi
    fi
    
    echo -n "Decoding mp3 file to wav (temp dir: $wavetemp)..."
    mpg123 -q -w $wavetemp/$i.wav $i
    echo "done."
    mv $tocfile $tocfile.tmp
    awk '/FILE / { $2="\"'$wavetemp/$i.wav'\""} { print $0 }' <$tocfile.tmp > $tocfile
    rm $tocfile.tmp
done

echo "Writing CD on device $device..."
cdrdao write -n --overburn --device $device --speed $speed --driver generic-mmc $option $tocfile

echo 
echo "Cleaning up..."

rm $tocfile

for i in $convert ; do

    if [ ! -f $i ] ; then
	i=`echo $i | tr '[:upper:]' '[:lower:]'`
    fi
    rm $wavetemp/$i.wav
done

