#!/bin/sh
# Copyright (c) 1998,1999 Robert Woodcock <rcw@debian.org>
# This code is hereby licensed for public consumption under either the
# GNU GPL v2 or greater, or Larry Wall's Artistic license - your choice.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

# Builtin defaults
CDDBURL="http://cddb.cddb.com/~cddb/cddb.cgi"
HELLOINFO="`whoami`+`hostname`+cdgrab+0.02"
ENCODER=lamer
CDROM=/dev/cdrom
CDDISCID=cd-discid
TAGGER=id3
if [ "$OUTPUTDIR" = "" ]; then
	OUTPUTDIR=`pwd`
fi
# Load system defaults
if [ -r /etc/cdgrab.conf ]; then
	. /etc/cdgrab.conf
fi
# Load user preference defaults
if [ -r $HOME/.cdgrab.conf ]; then
	. .cdgrab.conf
fi
# If the user specified a CD device on the command line, use it
if [ "$#" != "0" ]; then
	CDROM=$1
fi
# Query the CD to get the track info
echo -n "Getting CD track info... "
TRACKINFO=`$CDDISCID $CDROM`
TRACKS=`echo $TRACKINFO | cut -f2 -d' '`
echo $TRACKS tracks.
TRACKINFOPLUS=`echo $TRACKINFO | sed 's/ /+/g'`
echo -n "Looking up CD name..."
# Make CDDB query - protocol level = 4
CDINFO=`wget -O - "$CDDBURL?cmd=cddb+query+$TRACKINFOPLUS\&hello=$HELLOINFO\&proto=4" 2>/dev/null`
echo
RESPONSECODE=`echo $CDINFO | cut -f1 -d' '`
CDDBGENRE=`echo $CDINFO | cut -f2 -d' '`
DISCID=`echo $CDINFO | cut -f3 -d' '`
# Create a tempfile
CDDBDATA=`mktemp $OUTPUTDIR/cdgrab.XXXXXX` || exit 1
# Make CDDB read - protocol level = 4
wget -O $CDDBDATA "$CDDBURL?cmd=cddb+read+$CDDBGENRE+$DISCID\&hello=$HELLOINFO\&proto=4" 2>/dev/null
DARTISTALBUM="`grep ^DTITLE= $CDDBDATA | cut -f2 -d= | sed 's- / -~-g'`"
DARTIST=`echo $DARTISTALBUM | cut -f1 -d~`
DALBUM=`echo $DARTISTALBUM | cut -f2 -d~ | tr -d \[:cntrl:\]`
echo Title: $DALBUM
echo Artist: $DARTIST
ARTISTFILE=`echo $DARTIST | sed 's- -_-g' | tr -d \'\? | tr -d \[:cntrl:\]`
if [ \! -e "$OUTPUTDIR/$ARTISTFILE" ]; then
	mkdir "$OUTPUTDIR/$ARTISTFILE";
fi
X=0
while true
do
	TRACKNAME=`grep ^TTITLE$X= $CDDBDATA | cut -f2 -d= | tr -d \[:cntrl:\]`
	X=`expr $X + 1`
	TRACKFILE=`echo $TRACKNAME | sed 's- -_-g' | tr -d \'\?`
	echo "Ripping track $X..."
	echo
	WAVDATA=`mktemp $OUTPUTDIR/cdgrab.currenttrack.XXXXXX` || exit 1
	cdparanoia -d $CDROM -w $X $WAVDATA
	echo "Encoding track $X..."
	echo
	$ENCODER $WAVDATA $OUTPUTDIR/$ARTISTFILE/$TRACKFILE.mp3
	rm -f $WAVDATA
	echo "Tagging track $X... $TRACKNAME"
	echo
	id3 -A "$DALBUM" -a "$DARTIST" -t "$TRACKNAME" $OUTPUTDIR/$ARTISTFILE/$TRACKFILE.mp3
	if [ "$X" = "$TRACKS" ]; then
		echo
		echo "Finished."
		rm -f $CDDBDATA
		exit
	fi
done
