#!/bin/bash

# Copy CD tracks into a directory for later use with abcde (or a
# similar encoder).

# TeknoHog wrote this to use on an extra machine with CDROM, but no
# space etc. for the whole ripping/encoding suite. To distribute ripping
# somewhat. 

# When used successfully, this creates a directory with wave and 
# info files, that can be encoded later by running abcde -C <discid>.
# Abcde will fetch the metadata and encode the tracks, without needing the CD.

# Requires: cdparanoia, cd-discid

# default/selectable device... the -d parameter is passed
# automatically to cdparanoia via $@, but we need the $dev for
# cd-discid.

dev=/dev/cdrom
while getopts d: opt; do
    case "$opt" in
	d) dev="$OPTARG" ;;
	?) printf "Usage: %s [-d device]\n" $0 ;;
    esac
done

discid=`cd-discid $dev | awk '{print $1}'`

dir=abcde.$discid

mkdir $dir
cd $dir
cd-discid $dev > discid

if [ ! -f status ]; then
   echo cdparanoia-audio-tracks > status
fi

cdparanoia -B $@

# remove leading silence on some CDs
if [ -f track00.cdda.wav ]; then rm track00.cdda.wav; fi

# abcde status info and track name format
for file in *cdda.wav; do 
    mv $file ${file//cdda.wav/wav}
    echo $file | sed -e 's/track\([0-9]\+\).\+/readtrack-\1/' >> status
done

# no no no.. this only works if you have grabbed all tracks at once
#tracks=`ls *.wav | wc -w`
tracks=`cut -f2 -d" " < discid`

echo $tracks > cdparanoia-audio-tracks

# For a disc with fewer than 10 tracks, abcde expects the track number to be 
# without the leading zero.
if [ $tracks -lt 10 ]; then
    sed -i 's/readtrack-0/readtrack-/g' status

    for file in track0*.wav; do
	mv $file ${file//track0/track}
    done
fi