#!/bin/bash

if [[ "$2" = "" ]] ; then
   echo "Usage: $0 <num> <filename.m3u>"
   echo "num: number of CDs to burn.  0 to burn all mp3s."
   exit
fi

NUM="$1"
M3U="$2"

if [ ! -f "$M3U" ] ; then
   echo "Unable to find playlist: $M3U"
   exit
fi

# You may need sudo if you have issue with permissions
# CDRECORD="sudo /usr/bin/cdrecord"
CDRECORD="/usr/bin/cdrecord"

# overburn and speed may not be needed, but my car cd player 
# prefers me to burn at slower speeds and overburn can save a 
# disk if it goes over by a meg or two.
CDOPTS=" -overburn speed=12 -eject -dao -audio -pad -v "

# Adjust this according to your media, leave room for padding and TOC.
CDSIZE=695000

# temp directory.  We'll clean it out when we're done, but not delete it.
TMPDIR="tmp.burnCDs"
mkdir -p ${TMPDIR}

# usage: shuffle <filename>
function shuffle () {
   cat "${@}"|grep -v "^#" |grep -i "mp3$" | \
   while read mp3 ; do
      echo "$RANDOM $mp3"
   done | sort | cut -d" " -f2- 
}

# This is a function because we'll call it from two places.
# usage: writecd <track list>
function writecd () {
   echo ----------------------------------------------------------------------
   echo Writing $(echo $@|wc -w) tracks.
   echo ----------------------------------------------------------------------
   $CDRECORD $CDOPTS $@   # Write the CD now.
   rm -f $@               # Remove the cdr files.
   echo ----------------------------------------------------------------------
}


track=1
cd=1
while read file ; do
   if [ -f "${file}" ] ; then
      echo ----------------------------------------------------------------------
      echo "CD:      $cd"
      echo "Track:   $track"
      echo "File:    $file"

      # decode the MP3 into a CDR file (like a WAV)
      cdrfile=$(printf "${TMPDIR}/track"%04d".cdr" $track)
      mpg321 -q --cdr "$cdrfile" "$file"

      size=$(du -c ${TMPDIR}/*cdr |tail -n1|awk {'print $1'})
      echo "CD Size: $(($size/1024)) MB"

      if [ "$size" -gt "$CDSIZE" ] ; then
         writecd $filelist  # Write the CD and remove the files.
         filelist=""        # Clear the list for the next CD.

         cd=$(($cd+1))
         if [[ "$NUM" -gt "0" && "$cd" -gt "$NUM" ]] ; then
            echo "Done."
            break 2
         fi
      fi
      filelist="$filelist $cdrfile"
   fi
   track=$(($track+1))

done < <(shuffle "$M3U")

if [ "${filelist}" != "" ] ; then
   writecd
fi

# Clean up.
rm ${TMPDIR}/track*cdr
