#!bin/bash
# 
# Purpose: Command line ripping of audio CD to mp3
#
# This script pulls a list of track titles from audio CD via cddb.pl (http://armin.emx.at/cddb/ cddb_get)
# Items are pulled from the CD to wav files via cdparanoia
# Finally, wav files are converted to mp3 files.
#  
#------------------------------
# make directory for Artist
# make directory for Disk Title
# and get inside
#------------------------------
artist=`/usr/bin/cddb.pl -c /dev/sr0 -I |grep 'artist:' |sed 's/^artist:[\ ]*//'`
echo "${artist}"
title=`/usr/bin/cddb.pl -c /dev/sr0 -I |grep 'title:' |sed 's/^title:[\ ]*//'`
echo "${title}"
# Make dir for artist
if [ ! -d "${artist}" ]; then
    mkdir -p "${artist}"
fi
# Make dir for album title
if [ ! -d "${artist}"/"${title}" ]; then
    mkdir -p "${artist}"/"${title}"
fi
pushd "${artist}"/"${title}"
#------------------------------
# Step though each track list
#------------------------------
# for every track on disk
/usr/bin/cddb.pl -c /dev/sr0 -I | grep '^track\ ' | (while read FOO; do
   #
   # Store the track number
   #
   i=`echo "${FOO}" |sed 's/track \(.*\):.*/\1/'`   
   #
   # get the title
   #
   title=`echo "${FOO}" |sed 's/^track.*: //'`   
   #
   # pad title with track number zero padded
   #
   title=`printf "%02d - $title" $i`
   echo $title   
   #
   # Pull the track off the disk as wav   
   #
   if [ ! -f "${i}.wav" ]; then
       cdparanoia -d /dev/scd0 -w $i "${i}.wav"
   fi  
   #
   # Conver the track to mp3
   #
   if [ ! -f "${i}.mp3" ]; then
       ffmpeg -y -i "${i}.wav" -ab 256k -map_meta_data outputfile:inputfile  "${i}.mp3" < /dev/null;   
   fi
   #
   # Remove the wav
   #
   rm -rf "${i}.wav"
   #
   # This will fail if the title has certian characters
   #
   mv "${i}.mp3" "${title}.mp3"
done)
#
# Change back to beginning directory
#
popd
eject -T

