Added last patches
[abcde.git] / abcde
1 #!/bin/sh
2 # Copyright (c) 1998-2001 Robert Woodcock <rcw@debian.org>
3 # Copyright (c) 2003-2004 Jesus Climent <jesus.climent@hispalinux.es>
4 # This code is hereby licensed for public consumption under either the
5 # GNU GPL v2 or greater, or Larry Wall's Artistic license - your choice.
6 #
7 # You should have received a copy of the GNU General Public License
8 # along with this program; if not, write to the Free Software
9 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
10 #
11 # Copyright for this work is to expire January 1, 2010, after which it
12 # shall be public domain.
13
14 VERSION="2.3.0"
15
16 usage ()
17 {
18 echo "This is abcde v$VERSION."
19 echo "Usage: abcde [options] [tracks]"
20 echo "Options:"
21 echo "-1     Encode the whole CD in a single file"
22 echo "-a <action1[,action2]...>"
23 echo "       Actions to perform (cddb,read,normalize,encode,tag,move,playlist,clean)"
24 #echo "-A     Experimental actions (retag, transcode)"
25 echo "-b     Batch mode: enable album normalization and nogap encoding"
26 echo "-c <file>"
27 echo "       Specify a configuration file (overrides system and user config files)"
28 echo "-C <discid#>"
29 echo "       Specify discid to resume from (only needed if you no longer have the cd)"
30 echo "-d <device>"
31 echo "       Specify CDROM device to grab"
32 echo "-D     Debugging mode (equivalent to sh -x abcde)"
33 echo "-e     Erase encoded track information from status file"
34 echo "-h     This help information"
35 #echo "-i    Tag files while encoding, when possible (local only) -NWY-"
36 echo "-j <#> Number of encoder processes to run at once (localhost)"
37 echo "-k     Keep the wav tracks for later use"
38 echo "-l     Use low disk space algorithm"
39 echo "-L     Use local CDDB storage directory"
40 echo "-n     No lookup. Don't query CDDB, just create and use template"
41 echo "-N     Noninteractive. Never prompt for anything"
42 echo "-m     Modify playlist to include CRLF endings, to comply with some players"
43 echo "-M     Create a CUE file"
44 echo "-o <type1[,type2]...>"
45 echo "       Output file type(s) (ogg,mp3,flac,spx,mpc). Defaults to ogg"
46 echo "-p     Pad track numbers with 0's (if less than 10 tracks)"
47 echo "-P     Use UNIX pipes to read+encode without wav files"
48 echo "-r <host1[,host2]...>"
49 echo "       Also encode on these remote hosts"
50 echo "-R     Add replaygain values to the tag info (only for ogg,flac)"
51 echo "-S <#> Set the CD speed"
52 #echo "-t    File types to preprocess (wav)"
53 #echo "-T    Set postprocessing options"
54 echo "-t <#> Start the track numbering at a given number"
55 echo "-T <#> Same as -t but modifies tag numbering"
56 echo "-v     Show version number and exit"
57 echo "-V     Be a bit more verbose about what is happening behind the scenes"
58 echo "-x     Eject CD after all tracks are read"
59 echo "-w <comment>"
60 echo "       Add a comment to the CD tracks"
61 echo "-W <#> Contatenate CDs: -T #01 -w \"CD #\"" 
62 echo ""
63 echo "Tracks is a space-delimited list of tracks to grab."
64 echo "Ranges specified with hyphens are allowed."
65 #echo "Double hyphens are used to concatenate tracks"
66 }
67
68 # Funtions to replace the need of seq, which is too distribution dependant.
69 f_seq_row ()
70 {
71         i=$1
72         while [ $i -ne `expr $2 + 1` ]
73         do
74                 echo $i
75                 i=`expr $i + 1`
76         done
77 }
78
79 f_seq_line ()
80 {
81         i=$1
82         while [ $i -ne `expr $2 + 1` ]
83         do
84                 printf $i" "
85                 i=`expr $i + 1`
86         done
87         echo
88 }
89
90 # Functions to replace the need of awk {print $1} and {print $NF}
91 get_first()
92 {
93 if [ X"$1" = "X" ]; then
94         for first in `cat`; do
95                 break
96         done
97 else
98         first=$1
99 fi
100 echo $first
101 }
102
103 get_last()
104 {
105 if [ X"$1" = "X" ]; then
106         for stdin in `cat`; do
107                 last=$stdin
108         done
109 else
110         for last in $@ ; do :; done
111 fi
112 echo $last
113 }
114
115 # checkstatus [blurb]
116 # Returns "0" if the blurb was found, returns 1 if it wasn't
117 # Puts the blurb content, if available, on stdout.
118 # Otherwise, returns "".
119 checkstatus ()
120 {
121         # Take the last line in the status file if there's multiple matches
122         PATTERN="^$1(=.*)?$"
123         BLURB=$(egrep $PATTERN "$ABCDETEMPDIR/status" | tail -n 1)
124
125         if [ -z "$BLURB" ]; then
126                 # No matches found
127                 return 1
128         else
129                 # Matches found
130                 # See if there's a = in it
131                 if [ "$(echo $BLURB | grep -c =)" != "0" ]; then
132                         echo "$(echo $BLURB | cut -f2- -d=)"
133                 fi
134                 return 0
135         fi
136 }
137
138 # checkerrors [blurb]
139 # Returns "0" if the blurb was found (meaning there was an error),
140 # returns 1 if it wasn't (yes this is a little backwards).
141 # Does not print the blurb on stdout.
142 # Otherwise, returns "".
143 checkerrors ()
144 {
145         if [ -e "$ABCDETEMPDIR/errors" ]; then :; else
146                 return 1
147         fi
148         # Take the last line in the status file if there's multiple matches
149         PATTERN="^$1(:.*)?$"
150         BLURB="$(egrep $PATTERN $ABCDETEMPDIR/errors | tail -n 1)"
151
152         if [ -z "$BLURB" ]; then
153                 # negative, we did not have a negative...
154                 return 1
155         else
156                 # affirmative, we had a negative...
157                 return 0
158         fi
159 }
160
161 # run_command [blurb] [command...]
162 # Runs a command, silently if necessary, and updates the status file
163 run_command ()
164 {
165         BLURB="$1"
166         shift
167         # See if this is supposed to be silent
168         if [ "$(checkstatus encode-output)" = "loud" ]; then
169                 "$@" >&2
170                 RETURN=$?
171         else
172                 # Special case for SMP, since
173                 # encoder output is never displayed, don't mute echos
174                 if [ -z "$BLURB" -a "$MAXPROCS" != "1" ]; then
175                         "$@" >&2
176                         RETURN=$?
177                 else
178                         "$@" >/dev/null 2>&1
179                         RETURN=$?
180                 fi
181         fi
182         case "$1" in
183         normalize)
184                 if [ "$RETURN" = "2" ]; then
185                         # File was already normalized.
186                         RETURN=0
187                 fi
188                 ;;
189         esac
190         if [ "$RETURN" != "0" ]; then
191                 # Put an error in the errors file. For various reasons we
192                 # can't capture a copy of the program's output but we can
193                 # log what we attempted to execute and the error code
194                 # returned by the program.
195                 if [ "$BLURB" ]; then
196                         TWEAK="$BLURB: "
197                 fi
198                 echo "${TWEAK}returned code $RETURN: $@" >> "$ABCDETEMPDIR/errors"
199                 return $RETURN # Do not pass go, do not update the status file
200         fi
201         if [ "$BLURB" ]; then
202                 echo $BLURB >> "$ABCDETEMPDIR/status"
203         fi
204 }
205
206 # relpath() and slash() are Copyright (c) 1999 Stuart Ballard and
207 # distributed under the terms of the GNU GPL v2 or later, at your option
208
209 # Function to determine if a word contains a slash.
210 slash ()
211 {
212         case "$1" in
213         */*) return 0;;
214         *) return 1;;
215         esac
216 }
217
218 # Function to give the relative path from one file to another.
219 # Usage: relpath fromfile tofile
220 # eg relpath music/Artist/Album.m3u music/Artist/Album/Song.mp3
221 # (the result would be Album/Song.mp3)
222 # Output is relative path to $2 from $1 on stdout
223
224 # This code has the following restrictions:
225 # Multiple ////s are not collapsed into single /s, with strange effects.
226 # Absolute paths and ../s are handled wrong in FR (but they work in TO)
227 # If FR is a directory it must have a trailing /
228
229 relpath ()
230 {
231         FR="$1"
232         TO="$2"
233
234         case "$TO" in
235         /*) ;; # No processing is needed for absolute paths
236         *)
237                 # Loop through common prefixes, ignoring them.
238                 while slash "$FR" && [ "$(echo "$FR" | cut -d/ -f1)" = "$(echo "$TO" | cut -d/ -f1)" ]
239                 do
240                         FR="$(echo "$FR" | cut -d/ -f2-)"
241                         TO="$(echo "$TO" | cut -d/ -f2-)"
242                 done
243                 # Loop through directory portions left in FR, adding appropriate ../s.
244                 while slash "$FR"
245                 do
246                         FR="$(echo "$FR" | cut -d/ -f2-)"
247                         TO="../$TO"
248                 done
249                 ;;
250         esac
251
252         echo $TO
253 }
254
255 # This code splits the a Various Artist track name from one of the following
256 # forms:
257 #
258 #  forward:        Artist / Track
259 #  forward-dash:   Artist - Track
260 #  reverse:        Track / Artist
261 #  reverse-dash:   Track - Artist
262 #  colon:          Artist: Track
263 #  trailing-paren: Artist (Track)
264 #
265 # variables used:
266 # VARIOUSARTISTS, VARIOUSARTISTSTYLE, TRACKNAME, TRACKARTIST
267 splitvarious ()
268 {
269         if [ "$VARIOUSARTISTS" = "y" ] && [ ! "$ONETRACK" = "y" ]; then
270                 case "$VARIOUSARTISTSTYLE" in
271                 forward)
272                         DTITLEARTIST=$(echo "$TRACKNAME" | sed 's- / -~-g')
273                         TRACKARTIST=$(echo "$DTITLEARTIST" | cut -f1 -d~)
274                         TRACKNAME=$(echo "$DTITLEARTIST" | cut -f2 -d~)
275                         ;;
276                 forward-dash)
277                         DTITLEARTIST=$(echo "$TRACKNAME" | sed 's, - ,~,g')
278                         TRACKARTIST=$(echo "$DTITLEARTIST" | cut -f1 -d~)
279                         TRACKNAME=$(echo "$DTITLEARTIST" | cut -f2 -d~)
280                         ;;
281                 reverse)
282                         DTITLEARTIST=$(echo "$TRACKNAME" | sed 's- / -~-g')
283                         TRACKARTIST=$(echo "$DTITLEARTIST" | cut -f2 -d~)
284                         TRACKNAME=$(echo "$DTITLEARTIST" | cut -f1 -d~)
285                         ;;
286                 reverse-dash)
287                         DTITLEARTIST=$(echo "$TRACKNAME" | sed 's, - ,~,g')
288                         TRACKARTIST=$(echo "$DTITLEARTIST" | cut -f2 -d~)
289                         TRACKNAME=$(echo "$DTITLEARTIST" | cut -f1 -d~)
290                         ;;
291                 colon)
292                         DTITLEARTIST=$(echo "$TRACKNAME" | sed 's-: -~-g')
293                         TRACKARTIST=$(echo "$DTITLEARTIST" | cut -f1 -d~)
294                         TRACKNAME=$(echo "$DTITLEARTIST" | cut -f2 -d~)
295                         ;;
296                 trailing-paren)
297                         DTITLEARTIST=$(echo "$TRACKNAME" | sed 's,^\(.*\) (\(.*\)),\1~\2,')
298                         TRACKARTIST=$(echo "$DTITLEARTIST" | cut -f2 -d~)
299                         TRACKNAME=$(echo "$DTITLEARTIST" | cut -f1 -d~)
300                         ;;
301                 esac
302         elif [ "$ONETRACK" = "y" ]; then
303                 TRACKARTIST="Various"
304         else
305                 TRACKARTIST="$DARTIST"
306         fi
307 }
308
309 do_getgenreid () {
310 local genre=$(echo "${@}" | tr '[A-Z]' '[a-z]')
311 local id=""
312         case ${genre} in
313                 "blues")                 id=0 ;;
314                 "classic rock")          id=1 ;;
315                 "country")               id=2 ;;
316                 "dance")                 id=3 ;;
317                 "disco")                 id=4 ;;
318                 "funk")                  id=5 ;;
319                 "grunge")                id=6 ;;
320                 "hip-hop")               id=7 ;;
321                 "jazz")                  id=8 ;;
322                 "metal")                 id=9 ;;
323                 "new age")               id=10 ;;
324                 "oldies")                id=11 ;;
325                 "other")                 id=12 ;;
326                 "pop")                   id=13 ;;
327                 "r&b")                   id=14 ;;
328                 "rap")                   id=15 ;;
329                 "reggae")                id=16 ;;
330                 "rock")                  id=17 ;;
331                 "techno")                id=18 ;;
332                 "industrial")            id=19 ;;
333                 "alternative")           id=20 ;;
334                 "ska")                   id=21 ;;
335                 "death metal")           id=22 ;;
336                 "pranks")                id=23 ;;
337                 "soundtrack")            id=24 ;;
338                 "euro-techno")           id=25 ;;
339                 "ambient")               id=26 ;;
340                 "trip-hop")              id=27 ;;
341                 "vocal")                 id=28 ;;
342                 "jazz+funk")             id=29 ;;
343                 "fusion")                id=30 ;;
344                 "trance")                id=31 ;;
345                 "classical")             id=32 ;;
346                 "instrumental")          id=33 ;;
347                 "acid")                  id=34 ;;
348                 "house")                 id=35 ;;
349                 "game")                  id=36 ;;
350                 "sound clip")            id=37 ;;
351                 "gospel")                id=38 ;;
352                 "noise")                 id=39 ;;
353                 "alt. rock")             id=40 ;;
354                 "bass")                  id=41 ;;
355                 "soul")                  id=42 ;;
356                 "punk")                  id=43 ;;
357                 "space")                 id=44 ;;
358                 "meditative")            id=45 ;;
359                 "instrum. pop")          id=46 ;;
360                 "instrum. rock")         id=47 ;;
361                 "ethnic")                id=48 ;;
362                 "gothic")                id=49 ;;
363                 "darkwave")              id=50 ;;
364                 "techno-indust.")        id=51 ;;
365                 "electronic")            id=52 ;;
366                 "pop-folk")              id=53 ;;
367                 "eurodance")             id=54 ;;
368                 "dream")                 id=55 ;;
369                 "southern rock")         id=56 ;;
370                 "comedy")                id=57 ;;
371                 "cult")                  id=58 ;;
372                 "gangsta")               id=59 ;;
373                 "top 40")                id=60 ;;
374                 "christian rap")         id=61 ;;
375                 "pop/funk")              id=62 ;;
376                 "jungle")                id=63 ;;
377                 "native american")       id=64 ;;
378                 "cabaret")               id=65 ;;
379                 "new wave")              id=66 ;;
380                 "psychadelic")           id=67 ;;
381                 "rave")                  id=68 ;;
382                 "showtunes")             id=69 ;;
383                 "trailer")               id=70 ;;
384                 "lo-fi")                 id=71 ;;
385                 "tribal")                id=72 ;;
386                 "acid punk")             id=73 ;;
387                 "acid jazz")             id=74 ;;
388                 "polka")                 id=75 ;;
389                 "retro")                 id=76 ;;
390                 "musical")               id=77 ;;
391                 "rock & roll")           id=78 ;;
392                 "hard rock")             id=79 ;;
393                 "folk")                  id=80 ;;
394                 "folk/rock")             id=81 ;;
395                 "national folk")         id=82 ;;
396                 "swing")                 id=83 ;;
397                 "fusion")                id=84 ;;
398                 "bebob")                 id=85 ;;
399                 "latin")                 id=86 ;;
400                 "revival")               id=87 ;;
401                 "celtic")                id=88 ;;
402                 "bluegrass")             id=89 ;;
403                 "avantgarde")            id=90 ;;
404                 "gothic rock")           id=91 ;;
405                 "progress. rock")        id=92 ;;
406                 "psychadel. rock")       id=93 ;;
407                 "symphonic rock")        id=94 ;;
408                 "slow rock")             id=95 ;;
409                 "big band")              id=96 ;;
410                 "chorus")                id=97 ;;
411                 "easy listening")        id=98 ;;
412                 "acoustic")              id=99 ;;
413                 "humour")                id=100 ;;
414                 "speech")                id=101 ;;
415                 "chanson")               id=102 ;;
416                 "opera")                 id=103 ;;
417                 "chamber music")         id=104 ;;
418                 "sonata")                id=105 ;;
419                 "symphony")              id=106 ;;
420                 "booty bass")            id=107 ;;
421                 "primus")                id=108 ;;
422                 "porn groove")           id=109 ;;
423                 "satire")                id=110 ;;
424                 "slow jam")              id=111 ;;
425                 "club")                  id=112 ;;
426                 "tango")                 id=113 ;;
427                 "samba")                 id=114 ;;
428                 "folklore")              id=115 ;;
429                 "ballad")                id=116 ;;
430                 "power ballad")          id=117 ;;
431                 "rhythmic soul")         id=118 ;;
432                 "freestyle")             id=119 ;;
433                 "duet")                  id=120 ;;
434                 "punk rock")             id=121 ;;
435                 "drum solo")             id=122 ;;
436                 "a capella")             id=123 ;;
437                 "euro-house")            id=124 ;;
438                 "dance hall")            id=125 ;;
439                 "goa")                   id=126 ;;
440                 "drum & bass")           id=127 ;;
441                 "club-house")            id=128 ;;
442                 "hardcore")              id=129 ;;
443                 "terror")                id=130 ;;
444                 "indie")                 id=131 ;;
445                 "britpop")               id=132 ;;
446                 "negerpunk")             id=133 ;;
447                 "polsk punk")            id=134 ;;
448                 "beat")                  id=135 ;;
449                 "christian gangsta rap") id=136 ;;
450                 "heavy metal")           id=137 ;;
451                 "black metal")           id=138 ;;
452                 "crossover")             id=139 ;;
453                 "contemporary christian")id=140 ;;
454                 "christian rock")        id=141 ;;
455                 "merengue")              id=142 ;;
456                 "salsa")                 id=143 ;;
457                 "thrash metal")          id=144 ;;
458                 "anime")                 id=145 ;;
459                 "jpop")                  id=146 ;;
460                 "synthpop")              id=147 ;;
461                 *)                       return 1 ;;
462         esac
463 echo ${id}
464 return 0
465 }
466
467 # do_tag [tracknumber]
468 # id3 tags a filename
469 # variables used:
470 # TRACKS, TRACKNAME, TRACKARTIST, TAGGER, TAGGEROPTS, VORBISCOMMENT, METAFLAC, 
471 # COMMENT, DALBUM, DARTIST, CDYEAR, CDGENRE (and temporarily) ID3TAGV
472 do_tag ()
473 {
474         COMMENTOUTPUT="$(eval echo ${COMMENT})"
475         run_command '' echo "Tagging track $1 of $TRACKS: $TRACKNAME..."
476         # If we want to start the tracks with a given number, we need to modify the
477         # TRACKNUM value before evaluation
478         if [ -n "$STARTTRACKNUMBER" -a -n "$STARTTRACKNUMBERTAG" ] ; then
479                 # Get the trackpadding from the current track
480                 CURRENTTRACKPADDING=$(echo -n $UTRACKNUM | wc -c)
481                 TRACKNUM=$( printf %0.${CURRENTTRACKPADDING}d $(expr ${UTRACKNUM} + ${STARTTRACKNUMBER} - $FIRSTTRACK ))
482         fi
483         for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
484         do
485         case "$OUTPUT" in
486         mp3)
487                 # id3v2 v0.1.9 claims to have solved the -c bug, so we merge both id3 and id3v2
488                 GENREID=$(do_getgenreid "${CDGENRE}")
489
490                 # FIXME # track numbers in mp3 come with 1/10, so we cannot happily substitute them with $TRACKNUM
491                 run_command tagtrack-$1 $TAGGER $TAGGEROPTS -c "$COMMENTOUTPUT" \
492                         -A "$DALBUM" -a "$TRACKARTIST" -t "$TRACKNAME" -y "$CDYEAR" \
493                         -g "$GENREID" -T "${TRACKNUM:-$1/$TRACKS}" \
494                         "$ABCDETEMPDIR/track$1.$OUTPUT"
495                 ;;
496         ogg)
497                 case "$OGGENCODERSYNTAX" in
498                         vorbize|oggenc)
499                                 # vorbiscomment can't do in-place modification, mv the file first
500                                 if [ -f "$ABCDETEMPDIR/track$1.$OUTPUT" -a ! -f "$ABCDETEMPDIR/track$1.uncommented.$OUTPUT" ]; then
501                                         mv "$ABCDETEMPDIR/track$1.$OUTPUT" "$ABCDETEMPDIR/track$1.uncommented.$OUTPUT"
502                                 fi
503                                 (
504                                 # These are from http://www.xiph.org/ogg/vorbis/doc/v-comment.html
505                                 echo ARTIST="$TRACKARTIST"
506                                 echo ALBUM="$DALBUM"
507                                 echo TITLE="$TRACKNAME"
508                                 if [ -n "$CDYEAR" ]; then
509                                         echo DATE="$CDYEAR"
510                                 fi
511                                 if [ -n "$CDGENRE" ]; then
512                                         echo GENRE="$CDGENRE"
513                                 fi      
514                                 echo TRACKNUMBER=${TRACKNUM:-$1}
515                                 echo CDDB=$CDDBDISCID
516                                 if [ "$(eval echo ${COMMENT})" != "" ]; then
517                                         case "$COMMENTOUTPUT" in
518                                                 *=*) echo "$COMMENTOUTPUT";;
519                                                 *)   echo COMMENT="$COMMENTOUTPUT";;
520                                         esac    
521                                 fi
522                                 ) | run_command tagtrack-$1 $VORBISCOMMENT $VORBISCOMMENTOPTS -w \
523                                         "$ABCDETEMPDIR/track$1.uncommented.$OUTPUT" "$ABCDETEMPDIR/track$1.$OUTPUT"
524                                 # Doublecheck that the commented file was created successfully before wiping the original
525                                 if [ -f "$ABCDETEMPDIR/track$1.$OUTPUT" ]; then
526                                         rm -f "$ABCDETEMPDIR/track$1.uncommented.$OUTPUT"
527                                 else
528                                         mv "$ABCDETEMPDIR/track$1.uncommented.$OUTPUT" "$ABCDETEMPDIR/track$1.$OUTPUT"
529                                 fi
530                                 ;;
531                 esac
532                 ;;
533         flac)
534 ## FIXME ##             [ "$FLACONOGG" = "y" ] && OUTPUT=ogg
535                 (
536                 echo ARTIST="$TRACKARTIST"
537                 echo ALBUM="$DALBUM"
538                 echo TITLE="$TRACKNAME"
539                 if [ -n "$CDYEAR" ]; then
540                         echo DATE="$CDYEAR"
541                 fi
542                 if [ -n "$CDGENRE" ]; then
543                         echo GENRE="$CDGENRE"
544                 fi      
545                 echo TRACKNUMBER=${TRACKNUM:-$1}
546                 echo CDDB=$CDDBDISCID
547                 if [ "$(eval echo ${COMMENT})" != "" ]; then
548                         case "$COMMENTOUTPUT" in
549                                 *=*) echo "$COMMENTOUTPUT";;
550                                 *)   echo COMMENT="$COMMENTOUTPUT";;
551                         esac    
552                 fi
553                 ) | run_command tagtrack-$1 $METAFLAC $METAFLACOPTS --import-tags-from=- "$ABCDETEMPDIR/track$1.$OUTPUT"
554                 ;;
555         spx)
556                 run_command tagtrack-$1 true
557                 ;;
558         mpc)
559                 run_command tagtrack-$1 true
560                 ;;
561         esac
562         done
563 }
564
565 # do_batch_encode
566 # variables used:
567 # OUTPUTTYPE, {FOO}ENCODERSYNTAX, ENCNICE, ENCODER, ENCODEROPTS
568 do_batch_encode ()
569 {
570         # The commands here don't go through run_command because they're never supposed to be silenced
571         echo "Batch encoding tracks: $TRACKQUEUE"
572         OUTPUT=$(echo $OUTPUTTYPE | grep "mp3" )
573         case "$OUTPUT" in
574         mp3)
575                 case "$MP3ENCODERSYNTAX" in
576                 lame)
577                         (
578                         cd "$ABCDETEMPDIR"
579                         TRACKFILES=
580                         for UTRACKNUM in $TRACKQUEUE
581                         do
582                                 TRACKFILES="$TRACKFILES track$UTRACKNUM.wav"
583                         done
584                         nice $ENCNICE $MP3ENCODER $MP3ENCODEROPTS --nogap $TRACKFILES
585                         RETURN=$?
586                         if [ "$RETURN" != "0" ]; then
587                                 echo "batch-encode: $ENCODER returned code $RETURN" >> errors
588                         else
589                                 for UTRACKNUM in $TRACKQUEUE
590                                 do
591                                         echo encodetrack-$UTRACKNUM >> status
592                                 done
593                         fi
594                         )
595                         ;;
596                 esac
597                 ;;
598         esac
599         # Other encoders fall through to normal encoding as the tracks
600         # have not been entered in the status file.
601 }
602
603 # do_encode [tracknumber] [hostname]
604 # If no hostname is specified, encode locally
605 # variables used:
606 # TRACKS, TRACKNAME, TRACKARTIST, DISTMP3, DISTMP3OPTS, {FOO}ENCODERSYNTAX, OUTPUTTYPE, ENCODEROPTS, DALBUM, DARTIST, ENCNICE, CDYEAR, CDGENRE, COMMENT
607 do_encode ()
608 {
609         if [ "$USEPIPES" = "y" ]; then
610                 case "$OUTPUT" in
611                         mp3)
612                                 TEMPARG="PIPE_$MP3ENCODERSYNTAX"
613                                 ;;
614                         ogg)
615                                 TEMPARG="PIPE_$OGGENCODERSYNTAX"
616                                 ;;
617                         flac)
618                                 TEMPARG="PIPE_$FLACENCODERSYNTAX"
619                                 ;;
620                         spx)
621                                 TEMPARG="PIPE_$SPEEXENCODER"
622                                 ;;
623                         mpc)
624                                 TEMPARG="PIPE_$MPPENCODER"
625                                 ;;
626                 esac
627                 IN=${!TEMPARG}
628         else
629                 IN="$ABCDETEMPDIR/track$1.wav"
630                 case "$OUTPUT" in
631                         mp3)
632                                 case "$MP3ENCODERSYNTAX" in
633                                         # FIXME # check if mp3enc needs -if for pipes
634                                         mp3enc)
635                                                 FILEARG="-if $IN"
636                                                 ;;
637                                         *)
638                                                 FILEARG=$IN
639                                                 ;;
640                                 esac
641                                 ;;
642                         *)
643                                 FILEARG=$IN
644                                 ;;
645                 esac
646         fi
647         # We need IN to proceed, if we are not using pipes.
648         if [ -s "$IN" -o X"$USEPIPES" = "Xy" ] ; then
649                 for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
650                 do
651                         OUT="$ABCDETEMPDIR/track$1.$OUTPUT"
652                         if [ X"$USEPIPES" = "Xy" ]; then
653                                 RUN_COMMAND=""
654                         else
655                                 run_command '' echo "Encoding track $1 of $TRACKS: $TRACKNAME..."
656                                 RUN_COMMAND="run_command encodetrack-$OUTPUT-$1"
657                         fi
658                         case "$OUTPUT" in
659                         mp3)
660                                 case "$2" in
661                                 %local*%)
662                                         case "$MP3ENCODERSYNTAX" in
663                                         lame|gogo) $RUN_COMMAND nice $ENCNICE $MP3ENCODER $MP3ENCODEROPTS "$IN" "$OUT" ;;
664                                         bladeenc) $RUN_COMMAND nice $ENCNICE $MP3ENCODER $MP3ENCODEROPTS -quit "$IN" ;;
665                                         l3enc|xingmp3enc) $RUN_COMMAND nice $ENCNICE $MP3ENCODER "$IN" "$OUT" $MP3ENCODEROPTS ;;
666                                         # FIXME # Relates to the previous FIXME since it might need the "-if" removed.
667                                         mp3enc) $RUN_COMMAND nice $ENCNICE $MP3ENCODER -if "$IN" -of "$OUT" $MP3ENCODEROPTS ;;
668                                         esac
669                                         ;;
670                                 *)
671                                         $RUN_COMMAND nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" >/dev/null 2>&1
672                                         ;;
673                                 esac
674                                 ;;
675                         ogg)
676                                 case "$2" in
677                                 %local*%)
678                                         case "$OGGENCODERSYNTAX" in
679                                         vorbize) $RUN_COMMAND nice $ENCNICE $OGGENCODER $OGGENCODEROPTS -w "$OUT" "$IN" ;;
680                                         oggenc) $RUN_COMMAND nice $ENCNICE $OGGENCODER $OGGENCODEROPTS -o "$OUT" "$IN" ;;
681                                         esac
682                                         ;;
683                                 *)
684                                         $RUN_COMMAND nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" >/dev/null 2>&1
685                                         ;;
686                                 esac
687                                 ;;
688                         flac)
689                                 case "$2" in
690                                 %local*%)
691                                         case "$FLACENCODERSYNTAX" in
692                                         flac) $RUN_COMMAND nice $ENCNICE $FLACENCODER  $FLACENCODEROPTS -o "$OUT" "$IN" ;; 
693                                         esac
694                                         ;;
695         
696                                 *)
697                                         echo -n "DISTMP3:"
698                                         echo "$DISTMP3 $DISTMP3OPTS $2 $IN $OUT >/dev/null 2>&1"
699                                         $RUN_COMMAND nice $DISTMP3NICE $DISTMP3 $DISTMP3OPTS "$2" "$IN" "$OUT" > /dev/null 2>&1
700                                         ;;
701                                 esac
702                                 ;;
703                         spx)
704                                 if [ "$(eval echo ${COMMENT})" != "" ]; then
705                                         case "$COMMENT" in
706                                                 *=*) ;;
707                                                 *)   COMMENT="COMMENT=$COMMENT" ;;
708                                         esac    
709                                         COMMENT="--comment \"$COMMENT\""
710                                 fi
711                                 # Quick hack to avoid tagging Ogg/Speex, since there is no other way to tag than inline tagging
712                                 if [ ! "$DOTAG" = "y" ]; then
713                                         $RUN_COMMAND nice $ENCNICE $SPEEXENCODER $SPEEXENCODEROPTS --author "$TRACKARTIST" --title "$TRACKNAME" "$COMMENT" "$IN" "$OUT"
714                                 else
715                                         $RUN_COMMAND nice $ENCNICE $SPEEXENCODER $SPEEXENCODEROPTS "$IN" "$OUT"
716                                 fi
717                                 ;;
718                         mpc)    
719                                 # MPP/MP+(Musepack) format (.mpc) is done locally, with inline
720                                 # tagging.
721                                 # I tried compiling the mppenc from corecodecs.org and got some
722                                 # errors, so I have not tried it myself.
723                                 ## FIXME ## Needs some cleanup to determine if an empty tag sent
724                                 ## FIXME ## to the encoder ends up empty.
725                                 $RUN_COMMAND nice $ENCNICE $MPPENCODER $MPPENCODEROPTS --artist "$TRACKARTIST" --album "$DALBUM" --title "$TRACKNAME" --track "$1" --genre "$CDGENRE" --year "$CDYEAR" --comment "$COMMENT" "$IN" "$OUT"
726                                 ;;
727                         esac
728                 done
729                 # Only remove .wav if the encoding succeeded
730                 if checkerrors "encodetrack-(.{3,4})-$1"; then 
731                         run_command encodetrack-$1 false
732                 else
733                         run_command encodetrack-$1 true
734                         if [ ! "$KEEPWAVS" = "y" ] ; then
735                                 rm -f "$IN"
736                         fi
737                 fi
738         else
739                 if [ "$(checkstatus encode-output)" = "loud" ]; then
740                         echo "HEH! The file we were about to encode disappeared:"
741                         echo ">> $IN"
742                 fi
743                 run_command encodetrack-$1 false
744         fi
745 }
746
747 # do_preprocess [tracknumber]
748 # variables used:
749 # TRACKS, TRACKNAME, TRACKARTIST, DISTMP3, DISTMP3OPTS, {FOO}ENCODERSYNTAX, OUTPUTTYPE, ENCODEROPTS, DALBUM, DARTIST, ENCNICE, CDYEAR, CDGENRE, COMMENT
750 #do_preprocess ()
751 #{
752 #       IN="$ABCDETEMPDIR/track$1.wav"
753 #       # We need IN to proceed.
754 #       if [ -s "$IN" ] ; then
755 #               for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
756 #               do
757 #                       #OUT="$ABCDETEMPDIR/track$1.$OUTPUT"
758 #                       run_command '' echo "Pre-processing track $1 of $TRACKS..."
759 #                       case "$POSTPROCESSFORMAT" in
760 #                       all|wav*)
761 #                               run_command preprocess-$OUTPUT-$1 nice $PRENICE $WAV_PRE $IF $OF ;;
762 #                       mp3)
763 #                               run_command preprocess-$OUTPUT-$1 nice $PRENICE $MP3_PRE $IF $OF ;;
764 #                       ogg)
765 #                               run_command preprocess-$OUTPUT-$1 nice $PRENICE $OGG_PRE $IF $OF ;;
766 #                       flac)
767 #                               run_command preprocess-$OUTPUT-$1 nice $PRENICE $FLAC_PRE $IF $OF ;;
768 #                       spx)
769 #                               run_command preprocess-$OUTPUT-$1 nice $PRENICE $SPX_PRE $IF $OF ;;
770 #                       esac
771 #               done
772 #               # Only remove .wav if the encoding succeeded
773 #               if checkerrors "preprocess-(.{3,4})-$1"; then 
774 #                       run_command preprocess-$1 false
775 #               else
776 #                       run_command preprocess-$1 true
777 #               fi
778 #       else
779 #               if [ "$(checkstatus encode-output)" = "loud" ]; then
780 #                       echo "HEH! The file we were about to pre-process disappeared:"
781 #                       echo ">> $IN"
782 #               fi
783 #               run_command preprocess-$1 false
784 #       fi
785 #}
786
787
788 # do_postprocess [tracknumber]
789 # variables used:
790 # TRACKS, TRACKNAME, TRACKARTIST, DISTMP3, DISTMP3OPTS, {FOO}ENCODERSYNTAX, OUTPUTTYPE, ENCODEROPTS, DALBUM, DARTIST, ENCNICE, CDYEAR, CDGENRE, COMMENT
791 #do_postprocess ()
792 #{
793 #       for POSTPROCESSFORMAT in $(echo $POSTPROCESSFORMATS | tr , \ )
794 #       do
795 #               IN="$ABCDETEMPDIR/track$1.$POSTPROCESSFORMAT"
796 #               # We need IN to proceed.
797 #               if [ -s "$IN" ] ; then
798 #                       #OUT="$ABCDETEMPDIR/track$1.$OUTPUT"
799 #                       run_command '' echo "Post-processing track $1 of $TRACKS..."
800 #                       case "$POSTPROCESSFORMAT" in
801 #                               mp3)
802 #                                       run_command postprocess-$OUTPUT-$1 nice $POSTNICE $MP3_POST $IF $OF ;;
803 #                               ogg)
804 #                                       run_command postprocess-$OUTPUT-$1 nice $POSTNICE $OGG_POST $IF $OF ;;
805 #                               flac)
806 #                                       run_command postprocess-$OUTPUT-$1 nice $POSTNICE $FLAC_POST $IF $OF ;;
807 #                               spx)
808 #                                       run_command postprocess-$OUTPUT-$1 nice $POSTNICE $SPX_POST $IF $OF ;;
809 #                       esac
810 #                       # Only remove .wav if the encoding succeeded
811 #                       if checkerrors "postprocess-(.{3,4})-$1"; then 
812 #                               run_command postprocess-$1 false
813 #                       else
814 #                               run_command postprocess-$1 true
815 #                       fi
816 #               else
817 #                       if [ "$(checkstatus encode-output)" = "loud" ]; then
818 #                               echo "HEH! The file we were about to post-process disappeared:"
819 #                               echo ">> $IN"
820 #                       fi
821 #                       run_command postprocess-$1 false
822 #               fi
823 #       done
824 #}
825
826 # do_batch_gain
827 # variables used:
828 # MP3GAIN, MP3GAINOPTS, VORBISGAIN, VORBISGAINOPTS
829 do_batch_gain ()
830 {
831         # The commands here don't go through run_command because they're never supposed to be silenced
832         echo "Batch analizing gain in tracks: $TRACKQUEUE"
833         (
834         cd "$ABCDETEMPDIR"
835         BLURB=
836         TRACKFILES=
837         for UTRACKNUM in $TRACKQUEUE
838         do
839                 MP3FILES="$TRACKFILES track$UTRACKNUM.mp3"
840         done
841         # XXX: Hard-coded batch option!
842         $NORMALIZER -b $NORMALIZEROPTS $TRACKFILES
843         RETURN=$?
844         if [ "$RETURN" != "0" ]; then
845                 echo "batch-normalize: $NORMALIZER returned code $RETURN" >> errors
846         else
847                 for UTRACKNUM in $TRACKQUEUE
848                 do
849                         echo normalizetrack-$UTRACKNUM >> status
850                 done
851         fi
852         )
853 }
854
855 # do_batch_normalize
856 # variables used:
857 # NORMALIZER, NORMALIZEROPTS
858 do_batch_normalize ()
859 {
860         # The commands here don't go through run_command because they're never supposed to be silenced
861         echo "Batch normalizing tracks: $TRACKQUEUE"
862         (
863         cd "$ABCDETEMPDIR"
864         BLURB=
865         TRACKFILES=
866         for UTRACKNUM in $TRACKQUEUE
867         do
868                 TRACKFILES="$TRACKFILES track$UTRACKNUM.wav"
869         done
870         # XXX: Hard-coded batch option!
871         $NORMALIZER -b $NORMALIZEROPTS $TRACKFILES
872         RETURN=$?
873         if [ "$RETURN" != "0" ]; then
874                 echo "batch-normalize: $NORMALIZER returned code $RETURN" >> errors
875         else
876                 for UTRACKNUM in $TRACKQUEUE
877                 do
878                         echo normalizetrack-$UTRACKNUM >> status
879                 done
880         fi
881         )
882 }
883
884 # do_normalize [tracknumber]
885 # variables used:
886 # TRACKS, TRACKNAME, NORMALIZER, NORMALIZEROPTS
887 do_normalize ()
888 {
889         IN="$ABCDETEMPDIR/track$1.wav"
890         if [ -e "$IN" ] ; then
891                 run_command '' echo "Normalizing track $1 of $TRACKS: $TRACKNAME..."
892                 run_command normalizetrack-$1 $NORMALIZER $NORMALIZEROPTS "$IN"
893         else
894                 if [ "$(checkstatus encode-output)" = "loud" ]; then
895                         echo "HEH! The file we were about to normalize disappeared:"
896                         echo ">> $IN"
897                 fi
898                 run_command normalizetrack-$1 false "File $IN was not found"
899         fi
900 }
901
902 # do_move [tracknumber]
903 # Deduces the outfile from environment variables
904 # Creates directory if necessary
905 # variables used:
906 # TRACKNUM, TRACKNAME, TRACKARTIST, DALBUM, OUTPUTFORMAT, CDGENRE, CDYEAR
907 do_move ()
908 {
909         for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
910         do
911                 # Create ALBUMFILE, ARTISTFILE, TRACKFILE
912                 # Munge filenames as follows:
913                 # ' ' -> '_'
914                 # '/' -> '_'
915                 # ''' -> ''
916                 # '?' -> ''
917                 # Eat control characters
918                 ALBUMFILE=$(mungefilename "$DALBUM")
919                 ARTISTFILE=$(mungefilename "$TRACKARTIST")
920                 TRACKFILE=$(mungefilename "$TRACKNAME")
921                 GENRE=$(mungegenre "$GENRE")
922                 YEAR=$(echo $CDYEAR)
923                 # If we want to start the tracks with a given number, we need to modify the
924                 # TRACKNUM value before evaluation
925                 if [ -n "$STARTTRACKNUMBER" ] ; then
926                         # Get the trackpadding from the current track
927                         CURRENTTRACKPADDING=$(echo -n $UTRACKNUM | wc -c)
928                         TRACKNUM=$( printf %0.${CURRENTTRACKPADDING}d $(expr ${UTRACKNUM} + ${STARTTRACKNUMBER} - $FIRSTTRACK ))
929                 else
930                         TRACKNUM=${UTRACKNUM}
931                 fi
932                 # Supported variables for OUTPUTFORMAT are GENRE, ALBUMFILE, ARTISTFILE,
933                 # TRACKFILE, and TRACKNUM.
934                 if [ "$VARIOUSARTISTS" = "y" ]; then
935                         OUTPUTFILE=$(eval echo $VAOUTPUTFORMAT)
936                         else
937                         OUTPUTFILE=$(eval echo $OUTPUTFORMAT)
938                 fi
939                 # Check that the directory for OUTPUTFILE exists, if it doesn't, create it
940                 OUTPUTFILEDIR=$(dirname "$OUTPUTDIR/$OUTPUTFILE")
941                 # mkdir -p shouldn't return an error if the directory already exists
942                 mkdir -p "$OUTPUTFILEDIR"
943                 run_command movetrack-$1 mv "$ABCDETEMPDIR/track$1.$OUTPUT" "$OUTPUTDIR/$OUTPUTFILE.$OUTPUT"
944         done
945 }
946
947 # do_playlist
948 # Create the playlist if wanted
949 # Variables used:
950 # PLAYLISTFORMAT, PLAYLISTDATAPREFIX, VAPLAYLISTFORMAT, VAPLAYLISTDATAPREFIX,
951 # VARIOUSARTISTS, OUTPUTDIR
952 do_playlist ()
953 {
954         for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
955         do
956                 # Create a playlist file for the playlist data to go into.
957                 # We used to wipe it out if it existed. Now we request permision if interactive.
958                 for LASTTRACK in $TRACKQUEUE; do :; done
959                 ALBUMFILE=$(mungefilename "$DALBUM")
960                 ARTISTFILE=$(mungefilename "$DARTIST")
961                 GENRE=$(mungegenre "$GENRE")
962                 if [ "$VARIOUSARTISTS" = "y" ] ; then
963                         PLAYLISTFILE=$(eval echo $VAPLAYLISTFORMAT)
964                 else
965                         PLAYLISTFILE=$(eval echo $PLAYLISTFORMAT)
966                 fi
967                 FINALPLAYLISTDIR=$(dirname "$OUTPUTDIR/$PLAYLISTFILE")
968                 mkdir -p "$FINALPLAYLISTDIR"
969                 if [ -s "$OUTPUTDIR/$PLAYLISTFILE" ]; then
970                         echo -n "Erase, Append to, or Keep the existing playlist file? [e/a/k] (e): " >&2
971                         if [ "$INTERACTIVE" = "y" ]; then
972                                 while [ "$DONE" != "y" ]; do
973                                         read ERASEPLAYLIST
974                                         case $ERASEPLAYLIST in
975                                                 e|E|a|A|k|K) DONE=y ;;
976                                                 *) ;;
977                                         esac
978                                 done
979                         else
980                                 echo e >&2
981                                 ERASEPLAYLIST=e
982                         fi
983                         # Once we erase the playlist, we use append to create the new one.
984                         [ "$ERASEPLAYLIST" = "e" -o "$ERASEPLAYLIST" = "E" ] && rm -f "$OUTPUTDIR/$PLAYLISTFILE" && ERASEPLAYLIST=a
985                 else
986                         # The playlist does not exist, so we can safelly use append to create the new list
987                         ERASEPLAYLIST=a
988                 fi
989                 if [ "$ERASEPLAYLIST" = "a" -o "$ERASEPLAYLIST" = "A" ]; then
990                         touch "$OUTPUTDIR/$PLAYLISTFILE"
991                         for UTRACKNUM in $TRACKQUEUE
992                         do
993                                 # Shares some code with do_move since the filenames have to match
994                                 CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
995                                 TRACKNAME=$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | cut -f2 -d= | tr -d \[:cntrl:\] | sed 's/\ \+$//')
996                                 splitvarious
997                                 TRACKFILE=$(mungefilename "$TRACKNAME")
998                                 ARTISTFILE=$(mungefilename "$TRACKARTIST")
999                                 # If we want to start the tracks with a given number, we need to modify the
1000                                 # TRACKNUM value before evaluation
1001                                 if [ -n "$STARTTRACKNUMBER" ] ; then
1002                                         # Get the trackpadding from the current track
1003                                         CURRENTTRACKPADDING=$(echo -n $UTRACKNUM | wc -c)
1004                                         TRACKNUM=$( printf %0.${CURRENTTRACKPADDING}d $(expr ${UTRACKNUM} + ${STARTTRACKNUMBER} - $FIRSTTRACK ))
1005                                 else
1006                                         TRACKNUM=${UTRACKNUM}
1007                                 fi
1008                                 if [ "$VARIOUSARTISTS" = "y" ]; then
1009                                         OUTPUTFILE=$(eval echo $VAOUTPUTFORMAT)
1010                                 else
1011                                         OUTPUTFILE=$(eval echo $OUTPUTFORMAT)
1012                                 fi
1013                                 if [ "$VARIOUSARTISTS" = "y" ]; then
1014                                         if [ "$VAPLAYLISTDATAPREFIX" ] ; then
1015                                                 echo ${VAPLAYLISTDATAPREFIX}$OUTPUTFILE.$OUTPUT >> "$OUTPUTDIR/$PLAYLISTFILE"
1016                                         else
1017                                                 relpath "$PLAYLISTFILE", "$OUTPUTFILE.$OUTPUT" >> "$OUTPUTDIR/$PLAYLISTFILE"
1018                                         fi
1019                                 else
1020                                         if [ "$PLAYLISTDATAPREFIX" ]; then
1021                                                 echo ${PLAYLISTDATAPREFIX}$OUTPUTFILE.$OUTPUT >> "$OUTPUTDIR/$PLAYLISTFILE"
1022                                         else
1023                                                 relpath "$PLAYLISTFILE", "$OUTPUTFILE.$OUTPUT" >> "$OUTPUTDIR/$PLAYLISTFILE"
1024                                         fi
1025                                 fi
1026                         done
1027                 fi
1028                 ## this will convert the playlist to have CRLF line-endings, if specified
1029                 ## (some hardware players insist on CRLF endings)
1030                 if [ "$DOSPLAYLIST" = "y" ]; then
1031                         awk '{substr("\r",""); printf "%s\r\n", $0}' "$OUTPUTDIR/$PLAYLISTFILE" > "$ABCDETEMPDIR/PLAYLISTFILE.tmp"
1032 #                       mv -f "$ABCDETEMPDIR/PLAYLISTFILE.tmp" "$OUTPUTDIR/$PLAYLISTFILE"
1033                         cat "$ABCDETEMPDIR/PLAYLISTFILE.tmp" | sed 's/\//\\/' > "$OUTPUTDIR/$PLAYLISTFILE"
1034                 fi
1035                 echo "playlistcomplete" >> "$ABCDETEMPDIR/status"
1036         done
1037 }
1038
1039 # do_discid
1040 # This essentially the start of things
1041 do_discid ()
1042 {
1043         # Query the CD to get the track info, unless the user specified -C
1044         # or we are using some actions which do not need the CDDB data at all
1045         #if [ ! X"$EXPACTIONS" = "X" ]; then
1046         #       :
1047         #elif [ -z "$DISCID" ]; then
1048         if [ -z "$DISCID" ]; then
1049                 vecho -n "Getting CD track info... "
1050                 if [ "$OSFLAVOUR" = "OSX" ]; then
1051                         disktool -u ${CDROM#/dev/}
1052                 fi
1053                 TRACKINFO=$($CDDISCID $CDROM)
1054                 if [ "$OSFLAVOUR" = "OSX" ]; then
1055                         disktool -m ${CDROM#/dev/}
1056                 fi
1057                 # Make sure there's a CD in there by checking cd-discid's return code
1058                 if [ "$?" = "1" ]; then
1059                         echo "abcde error: CD could not be read. Perhaps there's no CD in the drive?" >&2
1060                         exit 1
1061                 fi
1062                 WEHAVEACD=y
1063         else
1064                 TRACKINFO=$(cat "$WAVOUTPUTDIR/abcde.$DISCID/discid")
1065         fi
1066
1067         # Get a full enumeration of tracks, sort it, and put it in the TRACKQUEUE.
1068         # This needs to be done now because a section of the resuming code will need
1069         # it later.
1070
1071         # get the number of digits to pad TRACKNUM with - we'll use this later
1072         # a CD can only hold 99 tracks, but since we support a feature for starting
1073         # numbering the tracks from a given number, we might need to set it as a
1074         # variable for the user to define... or obtain it somehow.
1075         if [ "$PADTRACKS" = "y" ] ; then
1076                 TRACKNUMPADDING=2
1077         fi
1078
1079         ABCDETEMPDIR="$WAVOUTPUTDIR/abcde.$(echo $TRACKINFO | cut -f1 -d' ')"
1080         if [ -z "$TRACKQUEUE" ]; then
1081                 if [ ! "$STRIPDATATRACKS" = "y" ]; then
1082                         case "$CDROMREADERSYNTAX" in
1083                                 cdparanoia|debug)
1084                                         if [ "$WEHAVEACD" = "y" ]; then
1085                                                 vecho "Querying the CD for audio tracks..."
1086                                                 CDPARANOIAOUTPUT="$( $CDROMREADER -d $CDROM -Q --verbose 2>&1 )"
1087                                                 RET=$?
1088                                                 if [ ! "$RET" = "0" ];then
1089                                                         echo "Warning: Something went wrong while querying the CD... Maybe a DATA CD?"
1090                                                 fi
1091                                                 TRACKS="$( echo "$CDPARANOIAOUTPUT" | egrep '^[[:space:]]+[[:digit:]]' | tail -n 1 | get_first | tr -d "." | tr '\n' ' ' )"
1092                                                 CDPARANOIAAUDIOTRACKS="$TRACKS"
1093                                         else
1094                                                 if [ -f "$ABCDETEMPDIR/status" ] && checkstatus cdparanoia-audio-tracks ; then
1095                                                         TRACKS=$( cat $ABCDETEMPDIR/cdparanoia-audio-tracks )
1096                                                 else
1097                                                         TRACKS=$(echo $TRACKINFO | cut -f2 -d' ')
1098                                                 fi
1099                                         fi
1100                                         ;;
1101                                 *)      TRACKS=$(echo $TRACKINFO | cut -f2 -d' ') ;;
1102                         esac
1103                 else
1104                         TRACKS=$(echo $TRACKINFO | cut -f2 -d' ')
1105                 fi
1106                 if echo "$TRACKS" | grep "[[:digit:]]" > /dev/null 2>&1 ;then :;else
1107                         echo "The disc does not contain any tracks. Giving up..."
1108                         exit 0
1109                 fi
1110                 echo -n "Grabbing entire CD - tracks: "
1111                 if [ ! "$PADTRACKS" = "y" ] ; then
1112                         TRACKNUMPADDING=$(echo -n $TRACKS | wc -c | tr -d ' ')
1113                 fi
1114                 TRACKS=$(printf "%0.${TRACKNUMPADDING}d" $TRACKS)
1115                 X=0
1116                 while [ "$X" -ne "$TRACKS" ]
1117                 do
1118                         X=$(printf "%0.${TRACKNUMPADDING}d" $(expr $X + 1))
1119                         TRACKQUEUE=$(echo "$TRACKQUEUE" $X)
1120                 done
1121                 echo $TRACKQUEUE
1122         else
1123                 TRACKS=$(echo $TRACKINFO | cut -f2 -d' ')
1124                 # User-supplied track queue.
1125                 # Weed out non-numbers, whitespace, then sort and weed out duplicates
1126                 TRACKQUEUE=$(echo $TRACKQUEUE | sed 's-[^0-9 ]--g' | tr ' ' '\n' | grep -v ^$ | sort -n | uniq | tr '\n' ' ' | sed 's- $--g')
1127                 # Once cleaned, obtain the highest value in the trackqueue for number padding
1128                 for LASTTRACK in $TRACKQUEUE; do :; done
1129                 if [ ! "$PADTRACKS" = "y" ] ; then
1130                         TRACKNUMPADDING=$(echo -n $LASTTRACK | wc -c | tr -d ' ')
1131                 fi
1132                 # Now we normalize the trackqueue
1133                 for TRACK in $TRACKQUEUE ; do
1134                         TRACKNUM=$(printf %0.${TRACKNUMPADDING}d $(expr ${TRACK} + 0 ))
1135                         PADTRACKQUEUE=$(echo $PADTRACKQUEUE $TRACKNUM)
1136                 done
1137                 TRACKQUEUE=$PADTRACKQUEUE
1138                 echo Grabbing tracks: "$TRACKQUEUE"
1139         fi
1140
1141         QUEUEDTRACKS=$(echo $TRACKQUEUE | wc -w | tr -d ' ')
1142
1143         # We have the discid, create a temp directory after it to store all the temp
1144         # info
1145
1146         if [ -e "$ABCDETEMPDIR" ]; then
1147                 echo -n "abcde: attempting to resume from $ABCDETEMPDIR"
1148                 # It already exists, see if it's a directory
1149                 if [ ! -d "$ABCDETEMPDIR" ]; then
1150                         # This is a file/socket/fifo/device/etc, not a directory
1151                         # Complain and exit
1152                         echo >&2
1153                         echo "abcde: file $ABCDETEMPDIR already exists and does not belong to abcde." >&2
1154                         echo "Please investigate, remove it, and rerun abcde." >&2
1155                         exit 1
1156                 fi
1157                 echo -n .
1158                 # It's a directory, let's see if it's owned by us
1159                 if [ ! -O "$ABCDETEMPDIR" ]; then
1160                         # Nope, complain and exit
1161                         echo >&2
1162                         echo "abcde: directory $ABCDETEMPDIR already exists and is not owned by you." >&2
1163                         echo "Please investigate, remove it, and rerun abcde." >&2
1164                         exit 1
1165                 fi
1166                 echo .
1167                 # See if it's populated
1168                 if [ ! -f "$ABCDETEMPDIR/discid" ]; then
1169                         # Wipe and start fresh
1170                         echo "abcde: $ABCDETEMPDIR/discid not found. Abcde must remove and recreate" >&2
1171                         echo -n "this directory to continue. Continue? [y/n] (n)" >&2
1172                         if [ "$INTERACTIVE" = "y" ]; then
1173                                 read ANSWER
1174                         else
1175                                 echo y >&2
1176                                 ANSWER=y
1177                         fi
1178                         if [ "$ANSWER" != "y" ]; then
1179                                 exit 1
1180                         fi
1181                         rm -rf "$ABCDETEMPDIR" || exit 1
1182                         mkdir "$ABCDETEMPDIR"
1183                         if [ "$?" -gt "0" ]; then
1184                                 # Directory already exists or could not be created
1185                                 echo "abcde: Temp directory $ABCDETEMPDIR could not be created." >&2
1186                                 exit 1
1187                         fi
1188                 else
1189                         # Everything is fine. Check for ^encodetracklocation-
1190                         # and encode-output entries in the status file and
1191                         # remove them. These are not relevant across sessions.
1192                         if [ -f "$ABCDETEMPDIR/status" ]; then
1193                                 mv "$ABCDETEMPDIR/status" "$ABCDETEMPDIR/status.old"
1194                                 grep -v ^encodetracklocation- < "$ABCDETEMPDIR/status.old" \
1195                                         | grep -v ^encode-output > "$ABCDETEMPDIR/status"
1196                         fi
1197                         # Remove old error messages
1198                         if [ -f "$ABCDETEMPDIR/errors" ]; then
1199                                 rm -f "$ABCDETEMPDIR/errors"
1200                         fi
1201                 fi
1202         else
1203                 # We are starting from scratch
1204                 mkdir "$ABCDETEMPDIR"
1205                 if [ "$?" -gt "0" ]; then
1206                         # Directory already exists or could not be created
1207                         echo "abcde: Temp directory $ABCDETEMPDIR could not be created." >&2
1208                         exit 1
1209                 fi
1210                 cat /dev/null > "$ABCDETEMPDIR/status"
1211         fi
1212         if [ X"$CUEFILE" = "Xy" -a X"$WEHAVEACD" = "Xy" ]; then
1213                 if checkstatus cuefile >/dev/null ; then :; else
1214                         CUEFILE=cue-$(echo $TRACKINFO | cut -f3 -d' ').txt
1215                         $MKCUE $MKCUEOPTS > $ABCDETEMPDIR/$CUEFILE
1216                         echo cuefile=$CUEFILE >> "$ABCDETEMPDIR/status"
1217                 fi
1218         fi
1219         # If we got the CDPARANOIA status and it is not recorded, save it now
1220         if [ -n "$CDPARANOIAAUDIOTRACKS" ]; then
1221                 if checkstatus cdparanoia-audio-tracks; then :; else
1222                         if echo "$CDPARANOIAAUDIOTRACKS" >> "$ABCDETEMPDIR/cdparanoia-audio-tracks"; then
1223                                 echo "cdparanoia-audio-tracks" >> "$ABCDETEMPDIR/status"
1224                         fi
1225                 fi
1226         fi
1227         
1228         # Create the discid file
1229         echo "$TRACKINFO" > "$ABCDETEMPDIR/discid"
1230 }
1231
1232 # do_mkcue
1233
1234 do_mkcue()
1235 {
1236
1237 }
1238
1239 # do_cddbparse
1240 # Parses a CDDB file and outputs the title and the track names.
1241 # Variables: CDDBFILE
1242 do_cddbparse ()
1243 {
1244         CDDBPARSEFILE="$1"
1245         # List out disc title/author and contents
1246         if [ "$ONETRACK" = "y" ]; then
1247                 vecho "ONETRACK mode selected: displaying only the title of the CD..."
1248         fi
1249         echo "---- $(grep DTITLE "${CDDBPARSEFILE}" | cut '-d=' -f2- | tr -d \\r\\n ) ----"
1250         if [ ! "$ONETRACK" = "y" ]; then
1251                 for TRACK in $(f_seq_row 1 $TRACKS)
1252                 do
1253                         echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "${CDDBPARSEFILE}" | cut -f2- -d= | tr -d \\r\\n)"
1254                 done
1255         fi
1256 }
1257
1258 # do_localcddb
1259 # Check for a local CDDB file, and report success
1260 do_localcddb ()
1261 {
1262         if checkstatus cddb-readcomplete && checkstatus cddb-choice >/dev/null; then :; else
1263         
1264                 CDDBLOCALSUCCESS="n"
1265                 CDDBDISCID=$(echo $TRACKINFO | cut -d' ' -f1)
1266                 CDDBLOCALFILE="${CDDBLOCALDIR}/${CDDBDISCID}"
1267                 USELOCALRESP="y"
1268                 
1269                 # If the user has selected to check a local CDDB repo, we proceed with it
1270                 if [ -r "${CDDBLOCALFILE}" ]; then
1271                         # List out disc title/author and contents
1272                         do_cddbparse "${CDDBLOCALFILE}"
1273                         echo -n "Locally cached CDDB entry found, use it? [y/n] (y): "
1274                         if [ "$INTERACTIVE" = "y" ]; then
1275                                 read USELOCALRESP
1276                                 while [ "$USELOCALRESP" != "y" ] && [ "$USELOCALRESP" != "n" ] && [ "$USELOCALRESP" != "" ] ; do
1277                                         echo -n 'Invalid selection. Please answer "y" or "n": '
1278                                         read USELOCALRESP
1279                                 done
1280                                 [ x"$USELOCALRESP" = "x" ] && USELOCALRESP="y"
1281                         else
1282                                 echo "y" >&2
1283                         fi
1284                         if [ "$USELOCALRESP" = "y" ]; then
1285                                 #echo "Using local copy of CDDB data"
1286                                 cp "${CDDBLOCALFILE}" "$ABCDETEMPDIR/cddbread.1"
1287                                 echo 999 > "$ABCDETEMPDIR/cddbquery" # Assuming 999 isn't used by CDDB
1288                                 echo cddb-readcomplete >> "$ABCDETEMPDIR/status"
1289                                 do_cddbparse "${CDDBLOCALFILE}" > "$ABCDETEMPDIR/cddbchoices"
1290                                 echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
1291                                 CDDBLOCALSUCCESS="y"
1292                         else
1293                                 #echo "Not using local copy of CDDB data"
1294                                 CDDBLOCALSUCCESS="n"
1295                         fi
1296                 else
1297                         CDDBLOCALSUCCESS="n"
1298                 fi
1299         fi
1300 }
1301
1302 # do_cddbstat
1303 do_cddbstat ()
1304 {
1305         # Perform CDDB protocol version check if it hasn't already been done
1306         if checkstatus cddb-statcomplete; then :; else
1307                 if [ "$CDDBAVAIL" = "n" ]; then
1308                         ERRORCODE=no_query
1309                         echo 503 > "$ABCDETEMPDIR/cddbstat"
1310                 else
1311                         rc=1
1312                         CDDBUSER=$(echo $HELLOINFO | cut -f1 -d'@')
1313                         CDDBHOST=$(echo $HELLOINFO | cut -f2- -d'@')
1314                         while test $rc -eq 1 -a $CDDBPROTO -ge 3; do
1315                                 vecho "Checking CDDB server status..."
1316                                 $CDDBTOOL stat $CDDBURL $CDDBUSER $CDDBHOST $CDDBPROTO > "$ABCDETEMPDIR/cddbstat"
1317                                 RESPONSECODE=$(head -n 1 "$ABCDETEMPDIR/cddbstat" | cut -f1 -d' ')
1318                                 case "$RESPONSECODE" in
1319                                 210)    # 210 OK, status information follows (until terminating `.')
1320                                         rc=0;
1321                                         ;;
1322                                 501|*)  # 501 Illegal CDDB protocol level: <n>. 
1323                                         CDDBPROTO=`expr $CDDBPROTO - 1`
1324                                         ;;
1325                                 esac 
1326                         done
1327                         if test $rc -eq 1; then
1328                                 CDDBAVAIL="n" 
1329                         fi
1330                 fi
1331                 echo cddb-statcomplete >> "$ABCDETEMPDIR/status"
1332         fi
1333 }
1334
1335
1336 # do_cddbquery
1337 do_cddbquery ()
1338 {
1339         CDDBDISCID=$(echo $TRACKINFO | cut -d' ' -f1)
1340         CDDBLOCALFILE="${CDDBLOCALDIR}/${CDDBDISCID}"
1341         
1342         # Perform CDDB query if it hasn't already been done
1343         if checkstatus cddb-querycomplete; then :; else
1344                 if [ "$CDDBAVAIL" = "n" ]; then
1345                         ERRORCODE=no_query
1346                         echo 503 > "$ABCDETEMPDIR/cddbquery"
1347                 # The default CDDBLOCALSUCCESS is "n"
1348                 # This part will be triggered if the user CDDB repo does not 
1349                 # contain the entry, or if we are not trying to use the repo.
1350                 else
1351                         vecho "Querying the CDDB server..."
1352                         CDDBUSER=$(echo $HELLOINFO | cut -f1 -d'@')
1353                         CDDBHOST=$(echo $HELLOINFO | cut -f2- -d'@')
1354                         $CDDBTOOL query $CDDBURL $CDDBPROTO $CDDBUSER $CDDBHOST $TRACKINFO > "$ABCDETEMPDIR/cddbquery"
1355                         ERRORCODE=$?
1356                         case $ERRORCODE in
1357                                 0)  # success
1358                                 ;;
1359                                 12|13|14)
1360                                         # no match found in database,
1361                                         # wget/fetch error, or user requested not to use CDDB
1362                                         # Make up an error code (503) that abcde
1363                                         # will recognize in do_cddbread
1364                                         # and compensate by making a template
1365                                         echo 503 > "$ABCDETEMPDIR/cddbquery"
1366                                 ;;
1367                                 *) # strange and unknown error
1368                                         echo ERRORCODE=$ERRORCODE
1369                                         echo "abcde: $CDDBTOOL returned unknown error code"
1370                                 ;;
1371                         esac
1372                 fi
1373                 echo cddb-querycomplete >> "$ABCDETEMPDIR/status"
1374         fi
1375 }
1376
1377 # do_cddbread
1378 do_cddbread ()
1379 {
1380         # If it's not to be used, generate a template.
1381         # Then, display it (or them) and let the user choose/edit it
1382         if checkstatus cddb-readcomplete; then :; else
1383                 vecho "Obtaining CDDB results..."
1384                 # If CDDB is to be used, interpret the query results and read all
1385                 # the available entries.
1386                 rm -f "$ABCDETEMPDIR/cddbchoices"
1387                 CDDBCHOICES=1 # Overridden by multiple matches
1388                 RESPONSECODE=$(head -n 1 "$ABCDETEMPDIR/cddbquery" | cut -f1 -d' ')
1389                 case "$RESPONSECODE" in
1390                 200)
1391                         # One exact match, retrieve it
1392                         # 200 [section] [discid] [artist] / [title]
1393                         if checkstatus cddb-read-1-complete; then :; else
1394                                 echo -n "Retrieving 1 CDDB match..." >> "$ABCDETEMPDIR/cddbchoices"
1395                                 $CDDBTOOL read $CDDBURL $CDDBPROTO $CDDBUSER $CDDBHOST $(cut -f2,3 -d' ' "$ABCDETEMPDIR/cddbquery") > "$ABCDETEMPDIR/cddbread.1"
1396                                 echo "done." >> "$ABCDETEMPDIR/cddbchoices"
1397                                 echo cddb-read-1-complete >> "$ABCDETEMPDIR/status"
1398                                 echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
1399                         fi
1400                         # List out disc title/author and contents
1401                         echo ---- "$(cut '-d ' -f4- "$ABCDETEMPDIR/cddbquery")" ---- >> "$ABCDETEMPDIR/cddbchoices"
1402                         for TRACK in $(f_seq_row 1 $TRACKS)
1403                         do
1404                                 echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.1" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
1405                         done
1406                         echo >> "$ABCDETEMPDIR/cddbchoices"
1407                         ;;
1408                 202|403|409|503)
1409                         # No match
1410                         case "$RESPONSECODE" in
1411                         202) echo "No CDDB match." >> "$ABCDETEMPDIR/cddbchoices" ;;
1412                         403|409) echo "CDDB entry is corrupt, or the handshake failed." >> "$ABCDETEMPDIR/cddbchoices" ;;
1413                         503) echo "CDDB unavailable." >> "$ABCDETEMPDIR/cddbchoices" ;;
1414                         esac
1415                         $CDDBTOOL template $(cat "$ABCDETEMPDIR/discid") > "$ABCDETEMPDIR/cddbread.0"
1416                         # List out disc title/author and contents of template
1417                         echo ---- Unknown Artist / Unknown Album ---- >> "$ABCDETEMPDIR/cddbchoices"
1418                         UNKNOWNDISK=y
1419                         for TRACK in $(f_seq_row 1 $TRACKS)
1420                         do
1421                                 echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.0" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
1422                         done
1423                         echo >> "$ABCDETEMPDIR/cddbchoices"
1424                         echo cddb-read-0-complete >> "$ABCDETEMPDIR/status"
1425                         echo cddb-choice=0 >> "$ABCDETEMPDIR/status"
1426                         ;;
1427                 210|211)
1428                         # Multiple exact, (possibly multiple) inexact matches
1429                         IN=
1430                         if [ "$RESPONSECODE" = "211" ]; then IN=in; fi
1431                         if [ "$(wc -l < $ABCDETEMPDIR/cddbquery | tr -d ' ')" -eq 3 ]; then
1432                                 echo "One ${IN}exact match:" >> "$ABCDETEMPDIR/cddbchoices"
1433                                 tail -n +2 "$ABCDETEMPDIR/cddbquery" | head -n 1 >> "$ABCDETEMPDIR/cddbchoices"
1434                                 echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
1435                         else
1436                                 echo "Multiple ${IN}exact matches:" >> "$ABCDETEMPDIR/cddbchoices"
1437                         fi
1438                         vecho -n "Retrieving multiple matches... "
1439                         grep -v ^[.]$ "$ABCDETEMPDIR/cddbquery" | ( X=0
1440                         read DISCINFO # eat top line
1441                         while read DISCINFO
1442                         do
1443                                 X=$(expr $X + 1)
1444                                 if checkstatus cddb-read-$X-complete; then :; else
1445                                         $CDDBTOOL read $CDDBURL $CDDBPROTO $CDDBUSER $CDDBHOST $(echo $DISCINFO | cut -f1,2 -d' ') > "$ABCDETEMPDIR/cddbread.$X"
1446                                         echo cddb-read-$X-complete >> "$ABCDETEMPDIR/status"
1447                                 fi
1448                                 # List out disc title/author and contents
1449                                 echo \#$X: ---- "$DISCINFO" ---- >> "$ABCDETEMPDIR/cddbchoices"
1450                                 for TRACK in $(f_seq_row 1 $TRACKS)
1451                                 do
1452                                         echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.$X" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
1453                                 done
1454                                 echo >> "$ABCDETEMPDIR/cddbchoices"
1455                         done )
1456                         vecho "done."
1457                         CDDBCHOICES=$(expr $(cat "$ABCDETEMPDIR/cddbquery" | wc -l) - 2)
1458                         ;;
1459                 999)
1460                         # Using local copy.
1461                         for TRACK in $(f_seq_row 1 $TRACKS)
1462                         do
1463                                 echo $TRACK: "$(grep ^TTITLE$(expr $TRACK - 1)= "$ABCDETEMPDIR/cddbread.1" | cut -f2- -d= | tr -d \\r\\n)" >> "$ABCDETEMPDIR/cddbchoices"
1464                         done
1465                         echo >> "$ABCDETEMPDIR/cddbchoices"
1466                         echo cddb-read-1-complete >> "$ABCDETEMPDIR/status"
1467                         echo cddb-choice=1 >> "$ABCDETEMPDIR/status"
1468                         ;;
1469                 esac    
1470                 echo "cddb-readcomplete" >> "$ABCDETEMPDIR/status"
1471         fi
1472 }
1473
1474 # do_cddbedit
1475 do_cddbedit ()
1476 {
1477         if checkstatus cddb-edit >/dev/null; then
1478                 CDDBDATA="$ABCDETEMPDIR/cddbread.$(checkstatus cddb-choice)"
1479                 VARIOUSARTISTS="$(checkstatus variousartists)"
1480                 VARIOUSARTISTSTYLE="$(checkstatus variousartiststyle)"
1481                 return 0
1482         fi
1483         if [ "$INTERACTIVE" = "y" ]; then
1484                 # We should show the CDDB results both when we are not using the local CDDB repo
1485                 # or when we are using it but we could not find a proper match
1486                 if [ "$CDDBUSELOCAL" = "y" ] && [ ! "$CDDBLOCALSUCCESS" = "y" ] || [ ! "$CDDBUSELOCAL" = "y" ]; then
1487                         # Display the $ABCDETEMPDIR/cddbchoices file created above
1488                         # Pick a pager so that if the tracks overflow the screen the user can still view everything
1489                         if [ -r "$ABCDETEMPDIR/cddbchoices" ]; then
1490                                 CDDBCHOICES=$(expr $(cat "$ABCDETEMPDIR/cddbquery" | wc -l) - 2)
1491                                 CHOICE=$(checkstatus cddb-choice)
1492                                 if [ -n "$CHOICE" ] ; then
1493                                         case $CDDBCHOICES in
1494                                                 1) cat "$ABCDETEMPDIR/cddbchoices" ;;
1495                                                 *)
1496                                                 echo "Selected: #$CHOICE"
1497                                                 do_cddbparse "$ABCDETEMPDIR/cddbread.$CHOICE"
1498                                                 ;;
1499                                         esac
1500                                 else
1501                                         # The user has a choice to make, display the info in a pager if necessary
1502                                         if [ $(cat "$ABCDETEMPDIR/cddbchoices" | wc -l) -ge 24 ]; then
1503                                                 # Use the debian sensible-pager wrapper to pick the pager
1504                                                 # user has requested via their $PAGER environment variable
1505                                                 if [ -x "/usr/bin/sensible-pager" ]; then
1506                                                         /usr/bin/sensible-pager "$ABCDETEMPDIR/cddbchoices"
1507                                                 elif [ -x "$PAGER" ]; then
1508                                                         # That failed, try to load the preferred editor, starting
1509                                                         # with their PAGER variable
1510                                                         $PAGER "$ABCDETEMPDIR/cddbchoices"
1511                                                         # If that fails, check for less
1512                                                 elif [ -x /usr/bin/less ]; then
1513                                                         /usr/bin/less -f "$ABCDETEMPDIR/cddbchoices"
1514                                                         # more should be on all UNIX systems
1515                                                 elif [ -x /bin/more ]; then
1516                                                         /bin/more "$ABCDETEMPDIR/cddbchoices"
1517                                                 else
1518                                                         # No bananas, just cat the thing
1519                                                         cat "$ABCDETEMPDIR/cddbchoices" >&2
1520                                                 fi
1521                                         else
1522                                                 # It's all going to fit in one page, cat it
1523                                                 cat "$ABCDETEMPDIR/cddbchoices" >&2
1524                                         fi
1525                                         
1526                                         # I'll take CDDB read #3 for $400, Alex
1527                                         echo -n "Which entry would you like abcde to use (0 for none)? [0-$CDDBCHOICES]: " >&2
1528                                         read CDDBCHOICE
1529                                         [ X"$CDDBCHOICE" = "X" ] && CDDBCHOICE=1
1530                                         # Make sure we get a valid choice
1531                                         CDCHOICENUM=$(echo $CDDBCHOICE | xargs printf %d 2>/dev/null)
1532                                         while [ $CDCHOICENUM -lt 0 ] || [ $CDCHOICENUM -gt $CDDBCHOICES ]; do
1533                                                 echo "Invalid selection. Please choose a number between 1 and $CDDBCHOICES." >&2
1534                                                 echo -n "Selection [0-$CDDBCHOICES]: " >&2
1535                                                 read CDDBCHOICE
1536                                                 CDCHOICENUM=$(echo $CDDBCHOICE | xargs printf %d 2>/dev/null)
1537                                         done
1538                                         if [ "$CDCHOICENUM" = "0" ]; then
1539                                                 vecho "Creating empty CDDB template..."
1540                                                 UNKNOWNDISK=y
1541                                                 $CDDBTOOL template $(cat "$ABCDETEMPDIR/discid") > $ABCDETEMPDIR/cddbread.0
1542                                         else
1543                                                 echo "Selected: #$CDCHOICENUM ($(grep ^DTITLE= $ABCDETEMPDIR/cddbread.$CDCHOICENUM | cut -f2- -d= | tr -d \\r\\n))" >&2
1544                                                 do_cddbparse "$ABCDETEMPDIR/cddbread.$CDCHOICENUM"
1545                                         fi
1546                                         echo "cddb-choice=$CDCHOICENUM" >> "$ABCDETEMPDIR/status"
1547                                 fi
1548                         fi
1549                 else
1550                         # We need some code to show the selected option when local repository is selected and we have found a match
1551                         vecho "Using cached CDDB match..." >&2
1552                         # Display the $ABCDETEMPDIR/cddbchoices file created above
1553                         # Pick a pager so that if the tracks overflow the screen the user can still view everything
1554                         if [ -r "$ABCDETEMPDIR/cddbchoices" ]; then
1555                                 CDDBCHOICES=$(expr $(cat "$ABCDETEMPDIR/cddbquery" | wc -l) - 2)
1556                                 CHOICE=$(checkstatus cddb-choice)
1557                                 if [ "$USELOCALRESP" = "y" ]; then :; else
1558                                         if [ -n "$CHOICE" ] ; then
1559                                                 case $CDDBCHOICES in
1560                                                         0) 
1561                                                         UNKNOWNDISK=y
1562                                                         echo "Selected template."
1563                                                         ;;
1564                                                         1) cat "$ABCDETEMPDIR/cddbchoices" ;;
1565                                                         *)
1566                                                         echo "Selected: #$CHOICE"
1567                                                         do_cddbparse "$ABCDETEMPDIR/cddbread.$CHOICE"
1568                                                         ;;
1569                                                 esac
1570                                         fi
1571                                 fi
1572                         fi
1573                 fi
1574         else
1575                 # We're noninteractive - pick the first choice.
1576                 # But in case we run a previous instance and selected a choice, use it.
1577                 if [ -r "$ABCDETEMPDIR/cddbchoices" ]; then
1578                         # Show the choice if we are not using the locally stored one
1579                         # or when the local search failed to find a match.
1580                         PREVIOUSCHOICE=$(checkstatus cddb-choice)
1581                         if [ "$CDDBUSELOCAL" = "y" ] && [ "$CDDBLOCALSUCCESS" = "n" ] || [ ! "$CDDBUSELOCAL" = "y" ]; then
1582                                 #if [ "$PREVIOUSCHOICE" ]; then
1583                                         cat "$ABCDETEMPDIR/cddbchoices"
1584                                 #fi
1585                         fi
1586                         if [ ! -z "$PREVIOUSCHOICE" ] ; then
1587                                 CDCHOICENUM=$PREVIOUSCHOICE
1588                         else
1589                                 CDCHOICENUM=1
1590                                 echo "cddb-choice=$CDCHOICENUM" >> "$ABCDETEMPDIR/status"
1591                         fi
1592                         echo "Selected: #$CDCHOICENUM ($(grep ^DTITLE= $ABCDETEMPDIR/cddbread.$CDCHOICENUM | cut -f2- -d= | tr -d \\r\\n))" >&2
1593                 fi
1594         fi
1595
1596         # sanity check
1597         if checkstatus cddb-choice >/dev/null; then :; else
1598                 echo "abcde: internal error: cddb-choice not recorded." >&2
1599                 exit 1
1600         fi
1601         CDDBDATA="$ABCDETEMPDIR/cddbread.$(checkstatus cddb-choice)"
1602         echo -n "Edit selected CDDB data? [y/n] (" >&2
1603         if [ "$INTERACTIVE" = "y" ]; then
1604                 if [ "$UNKNOWNDISK" = "y" ]; then
1605                         echo -n "y): " >&2
1606                         read EDITCDDB
1607                         [ "$EDITCDDB" != "n" ] && EDITCDDB=y
1608                 else
1609                         echo -n "n): " >&2
1610                         read EDITCDDB
1611                 fi
1612         else
1613                 echo "n): n" >&2
1614                 EDITCDDB=n
1615         fi
1616         if [ "$EDITCDDB" = "y" ]; then
1617                 CDDBDATAMD5SUM=$($MD5SUM "$CDDBDATA" | cut -d " " -f 1);
1618                 
1619                 # Use the debian sensible-editor wrapper to pick the editor that the
1620                 # user has requested via their $EDITOR environment variable
1621                 if [ -x "/usr/bin/sensible-editor" ]; then
1622                         /usr/bin/sensible-editor "$CDDBDATA"
1623                 elif [ -n "$EDITOR" ]; then
1624                         if [ -x $(which "${EDITOR%%\ *}") ]; then
1625                                 # That failed, try to load the preferred editor, starting
1626                                 # with their EDITOR variable
1627                                 eval $(echo "$EDITOR") "$CDDBDATA"
1628                         fi
1629                 # If that fails, check for a vi
1630                 elif which vi >/dev/null 2>&1; then
1631                         vi "$CDDBDATA"
1632                 elif [ -x /usr/bin/vi ]; then
1633                         /usr/bin/vi "$CDDBDATA"
1634                 # nano should be on all (modern, i.e., sarge) debian systems
1635                 elif which nano >/dev/null 2>&1 ; then
1636                         nano "$CDDBDATA"
1637                 elif [ -x /usr/bin/nano ]; then
1638                         /usr/bin/nano "$CDDBDATA"
1639                 # mg should be on all OpenBSD systems
1640                 elif which mg >/dev/null 2>&1 ; then
1641                         mg "$CDDBDATA"
1642                 elif [ -x /usr/bin/mg ]; then
1643                         /usr/bin/mg "$CDDBDATA"
1644                 # bomb out
1645                 else
1646                         echo "No editor available. Check your EDITOR environment variable." >&2
1647                 fi
1648                 # delete editor backup file if it exists
1649                 if [ -w "$CDDBDATA~" ]; then
1650                         rm -f "$CDDBDATA~"
1651                 fi
1652         fi
1653
1654         # Some heuristics first. Look at Disc Title, and if it starts with
1655         # "Various", then we'll assume Various Artists
1656         if [ "$(grep ^DTITLE= "$CDDBDATA" | cut -f2- -d= | egrep -ci '^(various|soundtrack|varios|sonora|ost)')" != "0" ]; then
1657                 echo "Looks like a Multi-Artist CD" >&2
1658                 VARIOUSARTISTS=y
1659         else
1660                 echo -n "Is the CD multi-artist? [y/n] (n): " >&2
1661                 if [ "$INTERACTIVE" = "y" ]; then
1662                         read VARIOUSARTISTS
1663                 else
1664                         echo n >&2
1665                         VARIOUSARTISTS=n
1666                 fi
1667         fi
1668         if [ "$VARIOUSARTISTS" = "y" ] && [ ! "$ONETRACK" = "y" ]; then
1669                 # Set a default
1670                 DEFAULTSTYLE=1
1671                 # Need NUMTRACKS before cddb-tool will return it:
1672                 NUMTRACKS=$(egrep '^TTITLE[0-9]+=' "$CDDBDATA" | wc -l)
1673                 if [ "$(grep -c "^TTITLE.*\/" "$CDDBDATA")" -gt "$(expr $NUMTRACKS / 2 )" ]; then
1674                         # More than 1/2 tracks contain a "/", so guess forward
1675                         DEFAULTSTYLE=1
1676                 elif [ "$(grep -c "^TTITLE.*\-" "$CDDBDATA")" -gt "$(expr $NUMTRACKS / 2 )" ]; then
1677                         # More than 1/2 contain a "-", so guess forward-dash
1678                         DEFAULTSTYLE=2
1679                 elif [ "$(grep -c "^TTITLE.*(.*)" "$CDDBDATA")" -gt "$(expr $NUMTRACKS / 2 )" ]; then
1680                         # More than 1/2 contain something in parens, so guess trailing-paren
1681                         DEFAULTSTYLE=6
1682                 fi
1683
1684                 echo "1) Artist / Title" >&2
1685                 echo "2) Artist - Title" >&2
1686                 echo "3) Title / Artist" >&2
1687                 echo "4) Title - Artist" >&2
1688                 echo "5) Artist: Title" >&2
1689                 echo "6) Title (Artist)" >&2
1690                 echo "7) This is a single-artist CD" >&2
1691                 echo -n "Which style of multiple artist entries is it? [1-7] ($DEFAULTSTYLE): " >&2
1692                 if [ "$INTERACTIVE" = "y" ]; then
1693                         read VARIOUSARTISTSTYLE
1694                 else
1695                         echo $DEFAULTSTYLE >&2
1696                         VARIOUSARTISTSTYLE=$DEFAULTSTYLE
1697                 fi
1698                 VARIOUSARTISTSTYLE=$(echo 0$VARIOUSARTISTSTYLE | xargs printf %d)
1699                 # If they press Enter, then the default style (0) was chosen
1700                 while [ $VARIOUSARTISTSTYLE -lt 0 ] || [ $VARIOUSARTISTSTYLE -gt 7 ]; do
1701                         echo "Invalid selection. Please choose a number between 1 and 7."
1702                         echo -n "Selection [1-7]: "
1703                         read VARIOUSARTISTSTYLE
1704                         VARIOUSARTISTSTYLE=$(echo 0$VARIOUSARTISTSTYLE | xargs printf %d)
1705                 done
1706                 if [ "$VARIOUSARTISTSTYLE" = "0" ]; then
1707                         VARIOUSARTISTSTYLE=$DEFAULTSTYLE
1708                 fi
1709                 vecho "Selected: $VARIOUSARTISTSTYLE"
1710                 case "$VARIOUSARTISTSTYLE" in
1711                 1) # Artist / Title
1712                         VARIOUSARTISTSTYLE=forward
1713                         ;;
1714                 2) # Artist - Title
1715                         VARIOUSARTISTSTYLE=forward-dash
1716                         ;;
1717                 3) # Title / Artist
1718                         VARIOUSARTISTSTYLE=reverse
1719                         ;;
1720                 4) # Title - Artist
1721                         VARIOUSARTISTSTYLE=reverse-dash
1722                         ;;
1723                 5) # Artist: Title
1724                         VARIOUSARTISTSTYLE=colon
1725                         ;;
1726                 6) # Title (Artist)
1727                         VARIOUSARTISTSTYLE=trailing-paren
1728                         ;;
1729                 7) # Single Artist
1730                         VARIOUSARTISTS=n
1731                         ;;
1732                 esac
1733         fi
1734
1735         echo "variousartists=$VARIOUSARTISTS" >> "$ABCDETEMPDIR/status"
1736         echo "variousartiststyle=$VARIOUSARTISTSTYLE" >> "$ABCDETEMPDIR/status"
1737
1738         if [ "$EDITCDDB" = "y" ] && [ "$UNINTENTIONALLY_ANGER_THE_FREEDB_PEOPLE" = "y" ]; then
1739                 if [ $CDDBDATAMD5SUM != "" ]  && [ $CDDBDATAMD5SUM != $($MD5SUM "$CDDBDATA" | cut -d " " -f 1) ]; then
1740                         # This works but does not have the necessary error checking
1741                         # yet. If you are familiar with the CDDB spec
1742                         # (see http://www.freedb.org/src/latest/DBFORMAT) 
1743                         # and can create an error-free entry on your own, then put
1744                         # UNINTENTIONALLY_ANGER_THE_FREEDB_PEOPLE=y in your
1745                         # abcde.conf to enable it. Put CDDBSUBMIT=email@address in
1746                         # your abcde.conf to change the email address submissions are
1747                         # sent to.
1748
1749                         # submit the modified file, if they want
1750                         if [ "$NOSUBMIT" != "y" ]; then
1751                                 echo -n "Do you want to submit this entry to $CDDBSUBMIT? [y/n] (n): "
1752                                 read YESNO
1753                                 while [ "$YESNO" != "y" ] && [ "$YESNO" != "n" ] && [ "$YESNO" != "Y" ] && \
1754                                         [ "$YESNO" != "N" ] && [ "$YESNO" != "" ]
1755                                 do
1756                                         echo -n 'Invalid selection. Please answer "y" or "n": '
1757                                         read YESNO
1758                                 done
1759                                 if [ "$YESNO" = "y" ] || [ "$YESNO" = "Y" ]; then
1760                                         echo -n "Sending..."
1761                                         $CDDBTOOL send "$CDDBDATA" $CDDBSUBMIT
1762                                         echo "done."
1763                                 fi
1764                         fi
1765                 fi
1766         fi
1767         # Make sure the cache directory exists
1768         mkdir -p $CDDBLOCALDIR
1769         # Cache edited CDDB entry in the user's cddb dir
1770         if [ "$CDDBCOPYLOCAL" = "y" ] || [ "$COPYCDDBLOCAL" = "Y" ]; then
1771                 cat "$CDDBDATA" | tail -n $(expr $(cat "$CDDBDATA" | wc -l ) - 1 ) > ${CDDBLOCALDIR}/$(echo "$TRACKINFO" | cut -d' ' -f1)
1772         fi
1773
1774         echo "cddb-edit" >> "$ABCDETEMPDIR/status"
1775 }
1776
1777 # do_cdread [tracknumber]
1778 # do_cdread onetrack [firsttrack] [lasttrack]
1779
1780 do_cdread ()
1781 {
1782         # The commands here don't go through run_command because they're never supposed to be silenced
1783         # return codes need to be doublechecked anyway, however
1784         if [ "$1" = "onetrack" ]; then
1785                 # FIXME # Add the possibility of grabbing ranges of tracks in onetrack
1786                 # FIXME # Until then, we grab the whole CD in one track, no matter what
1787                 # the user said
1788                 # We need the first and last track for cdda2wav
1789                 FIRSTTRACK=$2
1790                 LASTTRACK=$3
1791                 UTRACKNUM=$FIRSTTRACK
1792                 case "$CDROMREADERSYNTAX" in
1793                         cdparanoia) READTRACKNUMS="$FIRSTTRACK-$LASTTRACK" ;;
1794                         cdda2wav) READTRACKNUMS="$FIRSTTRACK+$LASTRACK" ;;
1795                         *) echo "abcde error: $CDROMREADERSYNTAX does not support ONETRACK mode"
1796                            exit 1 ;;
1797                 esac
1798         else
1799                 UTRACKNUM=$1
1800         fi
1801         CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
1802         if [ "$USEPIPES" = "y" ]; then
1803                 TEMPARG="PIPE_$CDROMREADERSYNTAX"
1804                 FILEARG=${!TEMPARG}
1805                 REDIR=""
1806                 PIPE_MESSAGE="and encoding "
1807         else
1808                 WAVDATA="$ABCDETEMPDIR/track$UTRACKNUM.wav"
1809                 case "$CDROMREADERSYNTAX" in
1810                 ## FIXME ## Find the case for dagrab, to avoid exceptions
1811                         dagrab)
1812                                 FILEARG="-f $WAVDATA"
1813                                 ;;
1814                         *)
1815                                 FILEARG=$WAVDATA
1816                                 ;;
1817                 esac
1818                 REDIR=">&2"
1819         fi
1820         if [ "$1" = "onetrack" ]; then
1821                 echo "Grabbing ${PIPE_MESSAGE}tracks $UTRACKNUM - $LASTTRACK ..." >&2
1822         else
1823                 if [ -r "$CDDBDATA" ]; then
1824                         TRACKNAME=$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | head -n 1 | cut -f2 -d= | tr -d \[:cntrl:\])
1825                         echo "Grabbing ${PIPE_MESSAGE}track $UTRACKNUM: $TRACKNAME..." >&2
1826                 else
1827                         echo "Grabbing ${PIPE_MESSAGE}track $UTRACKNUM..." >&2
1828                 fi
1829         fi
1830         case "$CDROMREADERSYNTAX" in
1831                 cdparanoia) 
1832                         nice $READNICE $CDROMREADER -d $CDROM ${READTRACKNUMS:-$UTRACKNUM} $FILEARG $REDIR ;;
1833                 cdda2wav)
1834                         if [ "$OSFLAVOUR" = "OSX" ] ; then
1835                                 # Hei, we have to unmount the device before running anything like cdda2wav in OSX
1836                                 disktool -u ${CDROM#/dev/} 0
1837                                 # Also, in OSX the cdrom device for cdda2wav changes...
1838                                 CDDA2WAVCDROM="IODVDServices"
1839                         elif [ "$OSFLAVOUR" = "FBSD" ] ; then
1840                                 CDDA2WAVCDROM="$CDROMID"
1841                         else
1842                                 if [ "$CDROMID" = "" ]; then
1843                                         CDDA2WAVCDROM="$CDROM"
1844                                 else
1845                                         CDDA2WAVCDROM="$CDROMID"
1846                                 fi
1847                         fi
1848                         nice $READNICE $CDROMREADER -D $CDDA2WAVCDROM -t ${READTRACKNUMS:-$UTRACKNUM} $FILEARG $REDIR
1849                         ;;
1850                 ## FIXME ## We have an exception for dagrab, since it uses -f
1851                 ## FIXME ## Shall we just use -f $FILEARG ??
1852                 dagrab) nice $READNICE $CDROMREADER -d $CDROM -v $UTRACKNUM $FILEARG $REDIR
1853                         ;;
1854                 cddafs)
1855                         # Find the track's mounted path
1856                         REALTRACKNUM=$(expr $UTRACKNUM + 0)
1857                         FILEPATH=$(mount | grep "$CDROM on" | sed 's/^[^ ]* on \(.*\) (.*/\1/')
1858                         FILEPATH=$(find "$FILEPATH" | grep "/$REALTRACKNUM ");
1859                         # If the file exists, copy it
1860                         if [ -e "$FILEPATH" ] ; then
1861                                 nice $READNICE $CDROMREADER "$FILEPATH" $FILEARG $REDIR
1862                         else
1863                                 false
1864                         fi ;;
1865                 debug) nice $READNICE $CDROMREADER -d $CDROM -w $UTRACKNUM-[:1] $FILEARG $REDIR
1866                         ;;
1867         esac
1868         RETURN=$?
1869         # If we get some error or we get some missing wav 
1870         # (as long as we dont use pipes)
1871         if [ "$RETURN" != "0" -o \( ! -s "$WAVDATA" -a X"$USEPIPES" != "Xy" \) ]; then
1872                 # Thank goodness errors is only machine-parseable up to the
1873                 # first colon, otherwise this woulda sucked
1874                 if [ "$RETURN" = "0" -a ! -s "$WAVDATA" ]; then
1875                         RETURN=73 # fake a return code as cdparanoia return 0 also on aborted reads
1876                 fi
1877                 if [ "$USEPIPES" = "y" ]; then
1878                         echo "readencodetrack-$UTRACKNUM: $CDROMREADER returned code $RETURN" >> "$ABCDETEMPDIR/errors"
1879                 else
1880                         echo "readtrack-$UTRACKNUM: $CDROMREADER returned code $RETURN" >> "$ABCDETEMPDIR/errors"
1881                 fi
1882                 return $RETURN
1883         else
1884                 if [ "$USEPIPES" = "y" ]; then
1885                         echo readencodetrack-$UTRACKNUM >> "$ABCDETEMPDIR/status"
1886                 else
1887                         echo readtrack-$UTRACKNUM >> "$ABCDETEMPDIR/status"
1888                 fi
1889         fi
1890 }
1891
1892 # do_cdspeed
1893 # No values accepted, only uses env variables
1894 do_cdspeed () 
1895 {
1896         if "$CDSPEED" "$CDSPEEDOPTS" "$CDSPEEDVALUE" >/dev/null ; then
1897                 vecho "Setting CD speed to ${CDSPEEDVALUE}x"
1898         else
1899                 echo "abcde: unable to set the device speed" >&2
1900         fi
1901 }
1902
1903 # vecho [message]
1904 #
1905 # vecho outputs a message if EXTRAVERBOSE is selected
1906 vecho ()
1907 {
1908 if [ x"$EXTRAVERBOSE" != "x" ]; then
1909         echo $@
1910 fi
1911 }
1912
1913 # User-redefinable functions
1914 # Custom filename munging:
1915 mungefilename ()
1916 {
1917         #echo "$@" | sed s,:,\ -,g | tr \ /\* __+ | tr -d \'\"\?\[:cntrl:\]
1918         echo "$@" | sed s,:,\ -,g | tr \ / __ | tr -d \'\"\?\[:cntrl:\]
1919 }
1920
1921 # Custom genre munging:
1922 mungegenre ()
1923 {
1924         echo $CDGENRE | tr "[:upper:]" "[:lower:]"
1925 }
1926
1927 # pre_read
1928 # Empty pre_read function, to be defined in the configuration file.
1929 pre_read ()
1930 {
1931 :
1932 }
1933
1934 ###############################################################################
1935 # End of functions
1936 #
1937 # Start of execution
1938 ###############################################################################
1939
1940 # Builtin defaults
1941 CDDBURL="http://freedb.freedb.org/~cddb/cddb.cgi"
1942 CDDBSUBMIT=freedb-submit@freedb.org
1943 CDDBPROTO=5
1944 HELLOINFO="$(whoami)@$(hostname)"
1945 INTERACTIVE=y
1946 CDROMREADERSYNTAX=cdparanoia
1947 OUTPUTTYPE=ogg
1948 ENCODERSYNTAX=default
1949
1950 MP3ENCODERSYNTAX=default
1951 OGGENCODERSYNTAX=default
1952 FLACENCODERSYNTAX=default
1953 SPEEXENCODERSYNTAX=default
1954 MPPENCODERSYNTAX=default
1955 NORMALIZERSYNTAX=default
1956
1957 OUTPUTFORMAT='${ARTISTFILE}-${ALBUMFILE}/${TRACKNUM}.${TRACKFILE}'
1958 # Use the following VAOUTPUTFORMAT to revert to 2.0.x VA format:
1959 #VAOUTPUTFORMAT=${OUTPUTFORMAT}
1960 VAOUTPUTFORMAT='Various-${ALBUMFILE}/${TRACKNUM}.${ARTISTFILE}-${TRACKFILE}'
1961 ONETRACKOUTPUTFORMAT='${ARTISTFILE}-${ALBUMFILE}/${ALBUMFILE}'
1962 VAONETRACKOUTPUTFORMAT='Various-${ALBUMFILE}/${ALBUMFILE}'
1963 PLAYLISTFORMAT='${ARTISTFILE}-${ALBUMFILE}.${OUTPUT}.m3u'
1964 PLAYLISTDATAPREFIX=''
1965 VAPLAYLISTFORMAT='${ARTISTFILE}-${ALBUMFILE}.${OUTPUT}.m3u'
1966 VAPLAYLISTDATAPREFIX=''
1967 DOSPLAYLIST=n
1968 COMMENT=''
1969 ID3TAGV=2
1970 ENCNICE=10
1971 READNICE=10
1972 DISTMP3NICE=10
1973 VARIOUSARTISTS=n
1974 VARIOUSARTISTSTYLE=forward
1975 KEEPWAVS=n
1976 PADTRACKS=n
1977 CDDBCOPYLOCAL="n"
1978 CDDBLOCALDIR="$HOME/.cddb"
1979 CDDBUSELOCAL="n"
1980
1981 # If using scsi devices, cdda2wav needs a CDROMID, instead of a device node
1982 # i.e. CDROMID="1,0,0"
1983 CDROMID=""
1984
1985 # program paths - defaults to checking your $PATH
1986 # mp3
1987 LAME=lame
1988 GOGO=gogo
1989 BLADEENC=bladeenc
1990 L3ENC=l3enc
1991 XINGMP3ENC=xingmp3enc
1992 MP3ENC=mp3enc
1993 # ogg
1994 VORBIZE=vorbize
1995 OGGENC=oggenc
1996 # flac
1997 FLAC=flac
1998 # speex
1999 SPEEXENC=speexenc
2000 # mpp (Musepack)
2001 MPPENC=mppenc
2002
2003 ID3=id3
2004 ID3V2=id3v2
2005 CDPARANOIA=cdparanoia
2006 CDDA2WAV=cdda2wav
2007 DAGRAB=dagrab
2008 CDDAFS=cp
2009 CDDISCID=cd-discid
2010 CDDBTOOL=cddb-tool
2011 EJECT=eject
2012 MD5SUM=md5sum
2013 DISTMP3=distmp3
2014 VORBISCOMMENT=vorbiscomment
2015 METAFLAC=metaflac
2016 NORMALIZE=normalize-audio
2017 CDSPEED=eject
2018 VORBISGAIN=vorbisgain
2019 MKCUE=mkcue
2020
2021 # Options for programs called from abcde
2022 # mp3
2023 LAMEOPTS=
2024 GOGOOPTS=
2025 BLADEENCOPTS=
2026 L3ENCOPTS=
2027 XINGMP3ENCOPTS=
2028 MP3ENCOPTS=
2029 # ogg
2030 VORBIZEOPTS=
2031 OGGENCOPTS=
2032 # flac
2033 FLACOPTS=
2034 # speex
2035 SPEEXENCOPTS=
2036 # mpc
2037 MPPENCOPTS=
2038
2039 ID3OPTS=
2040 ID3V2OPTS=
2041 CDPARANOIAOPTS=
2042 CDDA2WAVOPTS=
2043 DAGRABOPTS=
2044 CDDAFSOPTS="-f"
2045 CDDBTOOLOPTS=
2046 EJECTOPTS=
2047 DISTMP3OPTS=
2048 NORMALIZEOPTS=
2049 CDSPEEDOPTS="-x"
2050 CDSPEEDVALUE=
2051 MKCUEOPTS=
2052 VORBISCOMMENTOPTS="-R"
2053 METAFLACOPTS="--no-utf8-convert"
2054
2055 # Default to one process if -j isn't specified
2056 MAXPROCS=1
2057
2058 # List of actions to perform - by default, run to completion
2059 ACTIONS=cddb,read,encode,tag,move,clean
2060
2061 # Asume fetch if under FreeBSD. curl is used for Mac OS X. wget is used for Linux/OpenBSD/NetBSD.
2062 # Let's use these checkings to determine the OS flavour, which will be used later
2063 if [ X$(uname) = "XFreeBSD" ] ; then
2064         HTTPGET=fetch
2065         NEEDCDROMID=y
2066         OSFLAVOUR=FBSD
2067 elif [ X$(uname) = "XDarwin" ] ; then
2068         HTTPGET=curl
2069         OSFLAVOUR=OSX
2070         # We should have disktool in OSX, but let's be sure...
2071         NEEDDISKTOOL=y
2072         CDROMREADERSYNTAX=cddafs
2073 elif [ X$(uname) = "XOpenBSD" ] ; then
2074         HTTPGET=wget
2075         MD5SUM=md5
2076 else
2077         HTTPGET=wget
2078 fi
2079
2080 # If CDDBAVAIL is set to n, no CDDB read is done
2081 # If USEID3 is set to n, no ID3 tagging is done
2082 CDDBAVAIL=y
2083 USEID3=y
2084 USEID3V2=y
2085
2086 if [ -z "$OUTPUTDIR" ]; then
2087         OUTPUTDIR=$(pwd)
2088 fi
2089
2090 if [ -z "$WAVOUTPUTDIR" ]; then
2091         WAVOUTPUTDIR="$OUTPUTDIR"
2092 fi
2093
2094 # Load system defaults
2095 if [ -r /etc/abcde.conf ]; then
2096         . /etc/abcde.conf
2097 fi
2098 # Load user preference defaults
2099 if [ -r $HOME/.abcde.conf ]; then
2100         . $HOME/.abcde.conf
2101 fi
2102
2103 # By this time, we need some HTTPGETOPTS already defined.
2104 # If the user has defined a non-default HTTPGET method, we should not be empty.
2105
2106 if [ "$HTTPGETOPTS" = "" ] ; then
2107         case $HTTPGET in
2108                 wget) HTTPGETOPTS="-q -O -";;
2109                 curl) HTTPGETOPTS="-f -s";;
2110                 fetch)HTTPGETOPTS="-q -o -";;
2111                 *) echo "abcde warning: HTTPGET in non-standard and HTTPGETOPTS are not defined." >&2 ;;
2112         esac
2113 fi
2114
2115 # If the CDROM has not been set yet, find a suitable one.
2116 # If this is a devfs system, default to /dev/cdroms/cdrom0
2117 # instead of /dev/cdrom
2118 if [ "$CDROM" = "" ] ; then
2119         if [ -e /dev/cdroms/cdrom0 ]; then
2120                 CDROM=/dev/cdroms/cdrom0
2121         elif [ -e /dev/cdrom ]; then
2122                 CDROM=/dev/cdrom
2123         elif [ -e /dev/cd0c ]; then
2124                 CDROM=/dev/cd0c
2125         elif [ -e /dev/acd0c ]; then
2126                 CDROM=/dev/acd0c
2127         elif [ -e /dev/disk1 ]; then
2128                 CDROM=/dev/disk1
2129         fi
2130 fi
2131
2132 # Parse command line options
2133 #while getopts 1a:bc:C:d:Dhj:klLnNo:pr:S:t:T:vVx opt ; do
2134 while getopts 1a:A:bc:C:d:Dehj:klLmMnNo:pPr:Rs:S:t:T:vVxw:W: opt ; do
2135         case "$opt" in
2136                 1) ONETRACK=y ;;
2137                 a) ACTIONS="$OPTARG" ;;
2138                 A) EXPACTIONS="$OPTARG";;
2139                 b) BATCH=y ;;
2140                 c) if [ -e "$OPTARG" ] ; then . "$OPTARG" ; else echo "abcde error: config file \"$OPTARG\" cannot be found." >&2 ; exit 1 ; fi ;;
2141                 C) DISCID="${OPTARG#abcde.}" ;;
2142                 d) CDROM="$OPTARG" ;;
2143                 D) set -x ;;
2144                 e) ERASEENCODEDSTATUS=y ;;
2145                 h) usage; exit ;;
2146                 e) ERASEENCODEDSTATUS=y ;;
2147 #               f) FORCECDDBUSELOCAL=y ;;
2148                 i) INLINETAG=y ;;
2149                 j) MAXPROCS="$OPTARG" ;;
2150                 k) KEEPWAVS=y ;;
2151                 l) LOWDISK=y ;;
2152                 L) CDDBUSELOCAL=y ;;
2153                 n) CDDBAVAIL=n ;;
2154                 N) INTERACTIVE=n ;;
2155                 m) DOSPLAYLIST=y ;;
2156                 M) CUEFILE=y ;;
2157                 o) OUTPUTTYPE="$OPTARG" ;;
2158                 p) PADTRACKS=y ;;
2159                 P) USEPIPES=y ;;
2160                 r) REMOTEHOSTS="$OPTARG" ;;
2161                 R) REPLAYGAIN=y ;;
2162                 s) STARTTRACKNUMBER="$OPTARG" ;;
2163                 S) CDSPEEDVALUE="$OPTARG" ;;
2164 #               t) PREPROCESSFORMATS="$OPTARG"
2165 #                  PREPROCESS=y ;;
2166 #               T) POSTPROCESSFORMATS="$OPTARG" ;;
2167                 t) STARTTRACKNUMBER="$OPTARG" ;;
2168                 T) STARTTRACKNUMBER="$OPTARG" ; STARTTRACKNUMBERTAG="y" ;;
2169                 v) 
2170                    echo "This is abcde v$VERSION."
2171                    echo "Usage: abcde [options] [tracks]"
2172                    echo "abcde -h for extra help"
2173                    exit
2174                    ;;
2175                 V) EXTRAVERBOSE="y" ;;
2176                 x) EJECTCD="y" ;;
2177                 w) COMMENT="$OPTARG" ;;
2178                 W) if echo $OPTARG | grep -q "[[:digit:]]" ; then 
2179                      STARTTRACKNUMBER="${OPTARG}01" ; STARTTRACKNUMBERTAG="y" ; COMMENT="CD${OPTARG}"
2180                    else
2181                      echo "abcde error: argument of -W must be integer"
2182                          exit 1
2183                    fi
2184                    ;;
2185                 ?) usage; exit ;;
2186         esac
2187 done
2188
2189 shift $(($OPTIND - 1))
2190
2191 # Decide if we can continue.
2192 if [ "$ONETRACK" = "y" ]; then 
2193         # FIXME # remove check as soon as we find out about the other readers
2194         case "$CDROMREADERSYNTAX" in
2195                 dagrab|cddafs|debug) echo "abcde error: ONETRACK reading is not suported with $CDROMREADERSYNTAX yet"
2196                                          exit 1 ;;
2197         esac
2198         if [ "$BATCH" = "y" ]; then
2199                 echo "abcde error: BATCH mode is not compatible with ONETRACK mode"
2200                 BATCH=n
2201         fi
2202         # It does not matter how many tracks we want. In ONETRACK mode we grab them all
2203         # FIXME # allow ranges of tracks to be selected for onetrack ripping
2204         if [ $# -gt 0 ]; then
2205                 vecho "abcde warning: ONETRACK mode selected, grabbing all tracks..."
2206         fi
2207 else
2208         while [ $# -gt 0 ]; do
2209                 # Range parsing code courtesy of Vincent Ho
2210                 RSTART=$(echo $1 | cut -f1 -d-)
2211                 REND=$(echo $1 | cut -f2 -d-)
2212                 if [ "$RSTART" = "$REND" ]; then
2213                         NEWTRACKS="$RSTART"
2214                 else
2215                         NEWTRACKS=$(f_seq_line $RSTART $REND)
2216                 fi
2217                 TRACKQUEUE=$(echo "$TRACKQUEUE" "$NEWTRACKS")
2218                 shift
2219         done
2220 fi
2221
2222 # List of valid actions: cddb,read,normalize,encode,tag,move,playlist,clean
2223 # List of experimental actions: retag,transcode
2224
2225 # Determine what actions are to be done from $ACTIONS and set the
2226 # following environment variables for them:
2227 DOCDDB=n
2228 DOREAD=n
2229 DONORMALIZE=n
2230 DOPREPROCESS=n
2231 DOENCODE=n
2232 DOPOSTPROCESS=n
2233 DOTAG=n
2234 DOMOVE=n
2235 DOPLAYLIST=n
2236 DOCLEAN=n
2237
2238 for ACTION in $(echo $ACTIONS | tr , \ )
2239 do
2240         case $ACTION in
2241                 cddb) DOCDDB=y;;
2242                 read) DOREAD=y;;
2243                 normalize) DONORMALIZE=y; DOREAD=y;;
2244 #               preprocess) DOPREPROCESS=y; DOREAD=y;;
2245                 encode) DOENCODE=y; DOREAD=y;;
2246 #               postprocess) DOPREPROCESS=y; DOENCODE=y; DOREAD=y;;
2247                 tag) DOTAG=y; DOREAD=y; DOENCODE=y; DOCDDB=y;;
2248                 move) DOMOVE=y; DOTAG=y; DOREAD=y; DOENCODE=y; DOCDDB=y;;
2249                 playlist) DOCDDB=y; DOPLAYLIST=y;;
2250                 clean) DOCLEAN=y;;
2251         esac
2252 done
2253
2254 # Sanity checks:
2255
2256 # At this point a CDROM has to be defined, so we check it exists.
2257 if [ X"$CDROM" != "X" ] ; then 
2258         if [ "$CDROMREADERSYNTAX" = "cdda2wav" ] && [ "$NEEDCDROMID" = "y" ] ; then
2259                 if [ "$OSFLAVOUR" = "FBSD" ]; then
2260                         if ! echo "$CDROMID" | grep "^[0-9],[0-9],[0-9]$" >/dev/null 2>&1 ; then
2261                                 echo "abcde error: CDROMID not in the right format for $CDROMREADERSYNTAX"
2262                                 echo "Use \"cdrecord -scanbus\" to obtain a adecuate ID an set CDROMID accordingly"
2263                                 exit 1
2264                         fi
2265                 fi
2266         elif [ ! -e "$CDROM" -a X"$DOREAD" = "Xy" ]; then
2267                 echo "abcde error: CDROM device cannot be found." >&2
2268                 exit 1
2269         fi
2270 # avoid processing if we are not going to hit the CDROM.
2271 elif [ X"$DOREAD" = "Xy" ]; then
2272         echo "abcde error: CDROM has not been defined or cannot be found" >&2
2273         exit 1
2274 fi
2275
2276 # USEPIPES pre-tests, before we get into more serious stuff
2277 # Not compatible with:
2278 # - multiple outputs
2279 # - normalize
2280 # - lowdisk algorithm
2281 # - anything else?
2282 if [ X"$USEPIPES" = "Xy" ]; then
2283         if [ $(echo $OUTPUTTYPE | tr , \  | wc -w ) -gt 1 ]; then
2284                 echo "abcde error: Unix pipes not compatible with multiple outputs"
2285                 exit 1
2286         fi
2287         if [ X"$DONORMALIZE" = "Xy" ]; then
2288                 echo "abcde error: Unix pipes not compatible with normalizer"
2289                 # FIXME # Do we need to exit or shall we just disable the mode?
2290                 exit 1
2291         fi
2292         if [ X"$DOENCODE" = "Xn" ]; then
2293                 vecho "Disabling Unix pipes since we are not encoding!"
2294                 USEPIPES=n
2295         fi
2296         if [ X"$LOWDISK" = "Xy" ]; then
2297                 vecho "abcde error: Unix pipes not compatible with lowdisk algorithm"
2298                 exit 1
2299         fi
2300 fi
2301
2302 # Decide which CDROM reader we're gonna use
2303 case "$CDROMREADERSYNTAX" in
2304         cdparanoia|debug)
2305                 CDROMREADER="$CDPARANOIA"
2306                 CDROMREADEROPTS="$CDPARANOIAOPTS"
2307                 ;;
2308         cdda2wav)
2309                 CDROMREADER="$CDDA2WAV"
2310                 CDROMREADEROPTS="$CDDA2WAVOPTS"
2311                 ;;
2312         dagrab)
2313                 CDROMREADER="$DAGRAB"
2314                 CDROMREADEROPTS="$DAGRABOPTS"
2315                 ;;
2316         cddafs)
2317                 CDROMREADER="$CDDAFS"
2318                 CDROMREADEROPTS="$CDDAFSOPTS"
2319                 ;;
2320 esac
2321
2322 # There's only one normalize...
2323 case "$NORMALIZERSYNTAX" in
2324         default|normalize)
2325                 NORMALIZER="$NORMALIZE"
2326                 NORMALIZEROPTS="$NORMALIZEOPTS"
2327                 ;;
2328 esac
2329
2330 # Allow -o OUTPUT(1):OPTIONS(1),...,OUTPUT(N):OPTIONS(N) mode of operation
2331 if echo $OUTPUTTYPE | grep ":" > /dev/null 2>&1 ; then
2332         OLDFS="$FS"
2333         export FS=","
2334         for OUTPUT in "$OUTPUTTYPE"
2335         do
2336                 case "$OUTPUT" in
2337                         ogg:*)  OGGENCODEROPTSCLI="$( echo $OUTPUT | cut -d: -f2- )" ;;
2338                         mp3:*)  MP3ENCODEROPTSCLI="$( echo $OUTPUT | cut -d: -f2- )" ;;
2339                         flac:*) FLACENCODEROPTSCLI="$( echo $OUTPUT | cut -d: -f2- )" ;;
2340                         spx:*)  SPEEXENCODEROPTSCLI="$( echo $OUTPUT | cut -d: -f2- )" ;;
2341                         mpc:*)  MPPENCODEROPTSCLI="$( echo $OUTPUT | cut -d: -f2- )" ;;
2342                 esac
2343         done
2344         for OUTPUT in "$OUTPUTTYPE"
2345         do
2346                 TEMPOUTPUT=$( echo "$OUTPUT" | cut -d: -f1 )
2347                 TEMPOUTPUTTYPE="${TEMPOUTPUTTYPE:+$TEMPOUTPUTTYPE,}$TEMPOUTPUT"
2348         done
2349         OUTPUTTYPE="$TEMPOUTPUTTYPE"
2350         FS="$OLDFS"
2351 fi
2352
2353 # If nothing has been specified, use oggenc for oggs and lame for mp3s and flac for flacs and speexenc for speex and mppenc for mpps
2354
2355 # Getting ready for multiple output changes
2356 for OUTPUT in $(echo $OUTPUTTYPE | tr , \ )
2357 do
2358         case $OUTPUT in
2359                 ogg)    [ "$OGGENCODERSYNTAX" = "default" ] && OGGENCODERSYNTAX=oggenc
2360                                 [ "$DOTAG" = "y" ] && NEEDCOMMENTER=y
2361                                 [ "$REPLAYGAIN" = "y" ] && NEEDVORBISGAIN=y
2362                                 ;;
2363                 mp3)    [ "$MP3ENCODERSYNTAX" = "default" ] && MP3ENCODERSYNTAX=lame
2364                                 [ "$DOTAG" = "y" ] && NEEDTAGGER=y
2365                                 ;;
2366                 flac)   [ "$FLACENCODERSYNTAX" = "default" ] && FLACENCODERSYNTAX=flac
2367                                 [ "$DOTAG" = "y" ] && NEEDMETAFLAC=y
2368                                 ;;
2369                 spx)    [ "$SPEEXENCODERSYNTAX" = "default" ] && SPEEXENCODERSYNTAX=speexenc ;;
2370                 mpc)    [ "$MPPENCODERSYNTAX" = "default" ] && MPPENCODERSYNTAX=mppenc ;;
2371                 *)      echo "abcde error: Invalid OUTPUTTYPE defined" >&2
2372                         exit 1
2373                         ;;
2374         esac
2375 done
2376
2377 # decide which encoder
2378 case "$MP3ENCODERSYNTAX" in
2379         lame)
2380                 MP3ENCODEROPTS="${MP3ENCODEROPTSCLI:-$LAMEOPTS}"
2381                 MP3ENCODER="$LAME"
2382                 ;;
2383         gogo)
2384                 MP3ENCODEROPTS="${MP3ENCODEROPTSCLI:-$GOGOOPTS}"
2385                 MP3ENCODER="$GOGO"
2386                 ;;
2387         bladeenc)
2388                 MP3ENCODEROPTS="${MP3ENCODEROPTSCLI:-$BLADEENCOPTS}"
2389                 MP3ENCODER="$BLADEENC"
2390                 ;;
2391         l3enc)
2392                 MP3ENCODEROPTS="${MP3ENCODEROPTSCLI:-$L3ENCOPTS}"
2393                 MP3ENCODER="$L3ENC"
2394                 ;;
2395         xingmp3enc)
2396                 MP3ENCODEROPTS="${MP3ENCODEROPTSCLI:-$XINGMP3ENCOPTS}"
2397                 MP3ENCODER="$XINGMP3ENC"
2398                 ;;
2399         mp3enc)
2400                 MP3ENCODEROPTS="${MP3ENCODEROPTSCLI:-$MP3ENCOPTS}"
2401                 MP3ENCODER="$MP3ENC"
2402                 ;;
2403 esac
2404 case "$OGGENCODERSYNTAX" in
2405         vorbize)
2406                 OGGENCODEROPTS="${OGGENCODEROPTSCLI:-$VORBIZEOPTS}"
2407                 OGGENCODER="$VORBIZE"
2408                 ;;
2409         oggenc)
2410                 OGGENCODEROPTS="${OGGENCODEROPTSCLI:-$OGGENCOPTS}"
2411                 OGGENCODER="$OGGENC"
2412                 ;;
2413 esac
2414 case "$FLACENCODERSYNTAX" in
2415         flac)
2416                 FLACENCODEROPTS="${FLACENCODEROPTSCLI:-$FLACOPTS}"
2417                 FLACENCODER="$FLAC"     
2418                 ## FIXME ## FLAC streams can be encapsulated on a Ogg transport layer
2419                 if echo "$FLACENCODEROPTS" | egrep -q -- "(^| )--ogg($| )" ;then
2420                         FLACONOGG=y
2421                 fi
2422                 ;;
2423 esac
2424 case "$SPEEXENCODERSYNTAX" in
2425         speexenc)
2426                 SPEEXENCODEROPTS="${SPEEXENCODEROPTSCLI:-$SPEEXENCOPTS}"
2427                 SPEEXENCODER="$SPEEXENC"
2428                 ;;
2429 esac
2430 case "$MPPENCODERSYNTAX" in
2431         mppenc)
2432                 MPPENCODEROPTS="${MPPENCODEROPTSCLI:-$MPPENCOPTS}"
2433                 MPPENCODER="$MPPENC"
2434                 ;;
2435 esac
2436                 
2437 # and which tagger
2438
2439 if [ "$ID3TAGV" = "1" ]; then
2440         TAGGER="$ID3"
2441         TAGGEROPTS="$ID3OPTS"
2442 else
2443         TAGGER="$ID3V2"
2444         TAGGEROPTS="$ID3V2OPTS"
2445 fi
2446
2447 # Clean up nice options (either use '-n NICELEVEL or -NICELEVEL')
2448
2449 if [ "$ENCNICE" ]; then
2450         ENCNICE="-n $ENCNICE"
2451 fi
2452 if [ "$READNICE" ]; then
2453         READNICE="-n $READNICE"
2454 fi
2455 if [ "$DISTMP3NICE" ]; then
2456         DISTMP3NICE="-n $DISTMP3NICE"
2457 fi
2458
2459 # Don't check for stuff if it's not needed
2460 if [ "$REMOTEHOSTS" ]; then 
2461         NEEDDISTMP3=y
2462 fi
2463 if [ "$DONORMALIZE" = "y" ]; then
2464         NEEDNORMALIZER=y
2465 fi
2466 if [ "$EJECTCD" = "y" ]; then
2467         NEEDEJECT=y
2468 fi
2469 if [ ! "$CDDBAVAIL" = "n" ] && [ "$DOCDDB" = "y" ]; then
2470         NEEDHTTPGET=y
2471 fi
2472 if [ "$CUEFILE" = "y" ]; then
2473         NEEDMKCUE=y
2474 fi
2475
2476 if [ X"$CDSPEEDVALUE" != "X" ]; then
2477         case "$CDROMREADERSYNTAX" in
2478                 cdparanoia|debug) CDROMREADEROPTS="$CDPARANOIAOPTS -S $CDSPEEDVALUE" ;;
2479                 *) NEEDCDSPEED=y ;;
2480         esac
2481 fi
2482
2483 # Rippers with USEPIPE support
2484 # FIXME # Include here all the rippers we can figure out support pipes
2485 PIPE_cdparanoia="-"
2486
2487 # Encoders with USEPIPE support
2488 # FIXME # Include here all the encoders we can figure out support pipes
2489 PIPE_lame="-"
2490 PIPE_bladeenc="-"
2491 PIPE_oggenc="-"
2492
2493 # Figure out if we can use pipes with the ripper/encoder combination
2494 # exit otherwise
2495 if [ "$USEPIPES" = "y" ]; then
2496         PIPERIPPERSVARCHECK="PIPE_${CDROMREADER}"
2497         case "$OUTPUT" in
2498                 mp3)
2499                         PIPEENCODERSVARCHECK="PIPE_$MP3ENCODERSYNTAX" ;;
2500                 ogg)
2501                         PIPEENCODERSVARCHECK="PIPE_$OGGENCODERSYNTAX" ;;
2502                 flac)
2503                         PIPEENCODERSVARCHECK="PIPE_$FLACENCODERSYTNAX" ;;
2504                 spx)
2505                         PIPEENCODERSVARCHECK="PIPE_$SPEEXENCODER" ;;
2506                 mpc)
2507                         PIPEENCODERSVARCHECK="PIPE_$MPPENCODER" ;;
2508         esac
2509         if [ ! -n "${!PIPERIPPERSVARCHECK}" ] ; then
2510                 echo "abcde error: no support for pipes with given ripper" >&2
2511                 echo "read the USEPIPES file from the source tarball to help" >&2
2512                 echo "on a Debian system, read /usr/share/doc/abcde/USEPIPES.gz" >&2
2513                 exit 1;
2514         fi
2515         if [ ! -n "${!PIPEENCODERSVARCHECK}" ] ; then
2516                 echo "abcde error: no support for pipes with given encoder" >&2
2517                 echo "read the USEPIPES file from the source tarball to help" >&2
2518                 echo "on a Debian system, read /usr/share/doc/abcde/USEPIPES.gz" >&2
2519                 exit 1;
2520         fi
2521 fi
2522
2523
2524 # Make sure a buncha things exist
2525 for X in $CDROMREADER $CDDISCID ${NEEDTAGGER+$TAGGER} $MP3ENCODER \
2526         $OGGENCODER $FLACENCODER $SPEEXENCODER $MPPENCODER \
2527         ${NEEDHTTPGET+$HTTPGET} ${NEEDDISTMP3+$DISTMP3} \
2528         ${NEEDCOMMENTER+$VORBISCOMMENT} ${NEEDMETAFLAC+$METAFLAC} \
2529         ${NEEDNORMALIZER+$NORMALIZER} ${NEEDEJECT+$EJECT} \
2530         ${NEEDDISKTOOL+disktool} ${NEEDCDSPEED+$CDSPEED} \
2531         ${NEEDVORBISGAIN+$VORBISGAIN} ${NEEDMKCUE+$MKCUE}
2532 do
2533         # Cut off the command-line options we just added in
2534         X=$(echo $X | cut -d' ' -f2)
2535         if [ "$(which $X)" = "" ]; then
2536                 echo "abcde error: $X is not in your path." >&2
2537                 exit 1
2538         elif [ ! -x $(which $X) ]; then
2539                 echo "abcde error: $X is not executable." >&2
2540                 exit 1
2541         fi
2542 done
2543
2544 CDROMREADER="$CDROMREADER $CDROMREADEROPTS"
2545 CDDBTOOL="$CDDBTOOL $CDDBTOOLOPTS"
2546 HTTPGET="$HTTPGET $HTTPGETOPTS"
2547
2548 # Here it used to say:
2549 # One thousand lines in, we can start doing stuff with things
2550 # Well, right now we are at line 2157 ;)
2551
2552 # Export needed things so they can be read in this subshell
2553 export CDDBTOOL ABCDETEMPDIR TRACKQUEUE LOWDISK EJECTCD EJECT EJECTOPTS
2554 export CDROM CDDBDATA REMOTEHOSTS MAXPROCS HTTPGET MD5SUM
2555
2556 # User-definable function to set some things. Use it for
2557 #  - closing the CD tray with eject -t
2558 #  - set the CD speed value with eject -x
2559 vecho -n "Executing customizable pre-read function... "
2560
2561 pre_read # Execute the user-defined pre-read funtion. Close the CD with it.
2562
2563 vecho "done."
2564
2565 do_discid # Get ABCDETEMPDIR created and status file initialized
2566
2567 if [ "$DOCDDB" = "y" ]; then
2568         if [ $CDDBUSELOCAL = "y" ]; then
2569                 do_localcddb
2570         fi
2571         if checkstatus cddb-choice > /dev/null; then
2572                 :
2573         else 
2574                 if [ ! "$CDDBLOCALSUCCESS" = "y" ] ; then
2575                         do_cddbstat
2576                         do_cddbquery
2577                         do_cddbread
2578                 fi
2579         fi
2580         do_cddbedit
2581
2582         eval $($CDDBTOOL parse "$CDDBDATA")
2583 fi
2584
2585 # Before reading tracks, we set the speed of the device
2586
2587 if [ X"$CDSPEEDVALUE" != "X" ]; then
2588         case "$CDROMREADERSYNTAX" in
2589                 cdparanoia|debug) : ;;
2590                 *) do_cdspeed ;;
2591         esac
2592 fi
2593
2594 # Define the first and last track, since we might need them later in several places
2595 FIRSTTRACK=$( get_first $TRACKQUEUE )
2596 LASTTRACK=$( get_last $TRACKQUEUE )
2597
2598 if [ -f "$ABCDETEMPDIR/status" ] && [ X"$ERASEENCODEDSTATUS" = "Xy" ]; then
2599         mv "$ABCDETEMPDIR/status" "$ABCDETEMPDIR/status.old"
2600         grep -v ^encodetracklocation- < "$ABCDETEMPDIR/status.old" \
2601                 | grep -v ^encode-output > "$ABCDETEMPDIR/status"
2602 fi
2603
2604 # Create playlist if needed (backgroundable) and start reading in tracks
2605
2606 (
2607
2608 if [ ! "$ONETRACK" = "y" ]; then
2609         if [ "$DOPLAYLIST" = "y" ]; then
2610                 echo Creating playlist... >&2
2611                 do_playlist
2612         fi
2613 fi
2614
2615 # For the lowdisk option, only one program is running at once so the encoder
2616 # can be unsilenced right away.
2617 if [ "$LOWDISK" = "y" ] || [ "$ONETRACK" = "y" ]; then
2618         echo "encode-output=loud" >> "$ABCDETEMPDIR/status"
2619 fi
2620
2621 if [ "$ONETRACK" = "y" ]; then 
2622         TRACKS="$FIRSTTRACK"
2623         if checkstatus readtrack-$FIRSTTRACK; then :; else
2624                 do_cdread onetrack $FIRSTTRACK $LASTTRACK
2625         fi
2626 else
2627         for UTRACKNUM in $TRACKQUEUE
2628         do
2629                 if [ "$DOREAD" = "y" ]; then
2630                         if [ "$USEPIPES" = "y" ]; then
2631                                 if checkstatus readencodetrack-$UTRACKNUM; then :; else
2632                                         # Read, pipe, shut up!
2633                                         do_cdread $UTRACKNUM | do_encode $UTRACKNUM %local0% > /dev/null 2>&1
2634                                 fi
2635                         else
2636                                 if checkstatus readtrack-$UTRACKNUM; then :; else
2637                                         do_cdread $UTRACKNUM
2638                                 fi
2639                                 if [ "$?" != "0" ]; then
2640                                         # CD read failed - don't give the goahead to
2641                                         # the encoder
2642                                         echo NO
2643                                         exit
2644                                 fi
2645                         fi
2646                 fi
2647                 if [ "$BATCH" = "y" ]; then
2648                     :
2649                 else
2650                         echo NEXTTRACK # Get the encoder machine churning again
2651                         if [ "$DOREAD" = "y" ]; then
2652                                 if [ "$LOWDISK" = "y" ] && [ "$DOENCODE" = "y" ]; then
2653                                         until checkstatus encodetrack-$UTRACKNUM
2654                                         do
2655                                                 if checkerrors encodetrack-$UTRACKNUM; then
2656                                                         break
2657                                                 fi
2658                                                 sleep 2
2659                                         done
2660                                 fi
2661                         fi
2662                 fi
2663         done
2664 fi
2665
2666 # Now that we're done the encoding can be loud again -
2667 # if we're not using SMP.
2668 if [ "$MAXPROCS" = "1" ]; then
2669         echo "encode-output=loud" >> "$ABCDETEMPDIR/status"
2670 fi
2671
2672 # All tracks read, start encoding.
2673 if [ "$BATCH" = "y" ] || [ "$ONETRACK" = "y" ]; then
2674         echo NEXTTRACK
2675 fi
2676
2677 # We are now finished with the cdrom - it can be safely ejected. Note that
2678 # abcde will not have completed yet.
2679 if [ "$EJECTCD" = "y" ] && [ -x $(which $EJECT) ]; then
2680         # We check if the disk we are processing is actually the disk inside the 
2681         # CD tray. If not, we do not eject the CD, since it might be so that the
2682         # user ejected it manually.
2683         #CURRENTTRACKINFO=$($CDDISCID $CDROM)
2684         #if if [ "$?" != "1" ] && [ "$CURRENTTRACKINFO" = "$TRACKINFO" ] ; then 
2685         # More FreeBSD bits.
2686         if [ X"$(uname)" = X"FreeBSD" ] ; then
2687                 # FreeBSD eject uses the EJECT environment variable to name the CDROM
2688                 # but in this script EJECT is in the envionment and names the program
2689                 eject=$EJECT
2690                 unset EJECT
2691                 # The FreeBSD eject needs "adc0" not "/dev/adc0c"
2692                 cd="$(echo $CDROM | sed -e 's=.*/==;s=[a-h]$==;')"
2693                 $eject $EJECTOPTS $cd
2694         elif [ X"$(uname)" = X"Darwin" ] ; then
2695                 disktool -e ${CDROM#/dev/} 0
2696         else
2697                 $EJECT $EJECTOPTS $CDROM
2698         fi
2699         #fi
2700 fi
2701
2702 ) | (
2703
2704 ## Do we need to pre-process 
2705 #if [ x"$PREPROCESS" = "x" ] ; then
2706 #       cat
2707 #else
2708 #       for PRETRACKNUM in $TRACKQUEUE
2709 #       do
2710 #               read GOAHEAD
2711 #               if [ "$GOAHEAD" = "NO" ]; then break; fi
2712 #               PREPROCEED=
2713 #               until [ $PREPROCEED ]
2714 #               do
2715 #                       if checkstatus readtrack-$PRETRACKNUM; then PREPROCEED=y; break; fi
2716 #                       # all locations are working, wait and try again later
2717 #                       if [ ! $PREPROCEED ]; then sleep 3; fi
2718 #               done
2719 #               ( do_preprocess $PRETRACKNUM 
2720 #               echo "NEXTTRACK"
2721 #               ) &
2722 #       done
2723 #fi
2724 #
2725 #) | (
2726
2727 # In batch mode, we want all tracks to be read first.
2728 if [ "$BATCH" = "y" ]; then
2729         read GOAHEAD # For blocking - will contain either "NO" or "NEXTTRACK"
2730         if [ "$GOAHEAD" = "NO" ]; then break; fi
2731         for LASTTRACK in $TRACKQUEUE; do :; done
2732         if checkstatus readtrack-$LASTTRACK; then
2733                 if [ "$DONORMALIZE" = "y" ]; then
2734                         if checkstatus normalizetrack-$LASTTRACK; then :; else do_batch_normalize; fi
2735                         if checkerrors batch-normalize; then exit; fi
2736                 fi
2737                 if [ "$DOENCODE" = "y" ]; then
2738                         if checkstatus encodetrack-$LASTTRACK; then :; else do_batch_encode; fi
2739                         if checkerrors batch-encode; then exit; fi
2740                 fi
2741         fi
2742 fi
2743
2744 # If we are using ONETRACK, we can proceed with the normal encoding using just the $FIRSTTRACK as TRACKQUEUE
2745 if [ "$ONETRACK" = "y" ] ; then
2746         TRACKQUEUE="$FIRSTTRACK"
2747         TRACKS="$FIRSTTRACK"
2748 fi
2749
2750 # Do the encoding, including parallelization of remote encoding
2751 # Figure out where each track is going to be encoded
2752 ENCODELOCATIONS="$(echo $REMOTEHOSTS | tr , ' ')"
2753 if [ "$MAXPROCS" != "0" ]; then
2754         for NUM in $(f_seq_row 1 "$MAXPROCS")
2755         do
2756                 ENCODELOCATIONS="$ENCODELOCATIONS %local$NUM%"
2757         done
2758 fi
2759 # Strip whitespace
2760 ENCODELOCATIONS=$(echo $ENCODELOCATIONS)
2761 for UTRACKNUM in $TRACKQUEUE
2762 do
2763         # Wait for our cue
2764         read GOAHEAD # For blocking - will contain either "NO" or "NEXTTRACK"
2765         if [ "$GOAHEAD" = "NO" ]; then break; fi
2766         # find out where this track is to be encoded
2767         if [ "$DOENCODE" = "y" -a "$USEPIPES" != "y" ]; then
2768                 # Make sure we have a place to encode this, if not, exit stage right
2769                 if [ -z "$ENCODELOCATIONS" ]; then
2770                         continue
2771                 fi
2772                 PROCEED=
2773                 until [ $PROCEED ]
2774                 do
2775                         for LOCATION in $ENCODELOCATIONS
2776                         do
2777                                 PREVIOUSTRACK="$(checkstatus encodetracklocation-$LOCATION)"
2778                                 # check first if a track has ever been assigned to this location
2779                                 if [ -z "$PREVIOUSTRACK" ]; then PROCEED=y; break; fi
2780                                 # If it errored out, rebuild $ENCODELOCATIONS without this location in it
2781                                 if checkerrors encodetrack-$PREVIOUSTRACK; then
2782                                         for TEMPLOCATION in $ENCODELOCATIONS
2783                                         do
2784                                                 if [ "$TEMPLOCATION" != "$LOCATION" ]; then
2785                                                         TEMPENCODELOCATIONS="$TEMPENCODELOCATIONS $TEMPLOCATION"
2786                                                 fi
2787                                         done
2788                                         ENCODELOCATIONS=$(echo $TEMPENCODELOCATIONS)
2789                                         ABORT=y
2790                                         PROCEED=y
2791                                         break
2792                                 fi
2793                                 # We're still here, this location must have been previously assigned,
2794                                 # and last completed without error - check if it's done with the
2795                                 # previous track yet
2796                                 if checkstatus encodetrack-$PREVIOUSTRACK; then PROCEED=y; break; fi
2797                         done
2798                         # all locations are working, wait and try again later
2799                         if [ ! $PROCEED ]; then sleep 3; fi
2800                 done
2801                 # Record the location we're about to encode the next track at
2802                 echo "encodetracklocation-$LOCATION=$UTRACKNUM" >> "$ABCDETEMPDIR/status"
2803         fi
2804         # Don't proceed with the rest of the loop if we can't encode
2805         if [ "$ABORT" ]; then continue; fi
2806         # Set TRACKNUM, TRACKNAME
2807         if [ -e "$CDDBDATA" ]; then
2808                 if [ "$ONETRACK" = "y" ]; then 
2809                         TRACKNAME="$DALBUM"
2810                         TRACKNUM="$FIRSTTRACK"
2811                         splitvarious
2812                 else
2813 #                       TRACKNUM=$(printf %0.${TRACKNUMPADDING}d $(expr ${UTRACKNUM} + 0))
2814                         TRACKNUM=$UTRACKNUM
2815                         CDDBTRACKNUM=$(expr $UTRACKNUM - 1)
2816                         TRACKNAME="$(grep ^TTITLE$CDDBTRACKNUM= "$CDDBDATA" | cut -f2- -d= | tr -d \[:cntrl:\] | sed 's/\ \+$//')"
2817                         splitvarious
2818                 fi
2819         fi
2820         # You can't encode a file which needs to be normalized before finishing
2821         # You can't tag a file before it's finished encoding -
2822         # thus all of this is backgrounded together
2823         (
2824         if [ "$DONORMALIZE" = "y" ]; then
2825                 if checkstatus readtrack-$UTRACKNUM; then
2826                         if checkstatus normalizetrack-$UTRACKNUM; then :; else do_normalize $UTRACKNUM; fi
2827                 fi
2828         fi
2829         if [ "$DOENCODE" = "y" -a "$USEPIPES" != "y" ]; then
2830                 if checkstatus readtrack-$UTRACKNUM; then
2831                         #if checkstatus encodetrack-$UTRACKNUM; then :; else do_encode $UTRACKNUM $LOCATION; fi
2832                         if [ "$DONORMALIZE" = "y" ]; then
2833                                 if checkstatus normalizetrack-$UTRACKNUM; then
2834                                         if checkstatus encodetrack-$UTRACKNUM; then :; else do_encode $UTRACKNUM $LOCATION $OUTPUT; fi
2835                                 fi
2836                         else
2837                                 if checkstatus encodetrack-$UTRACKNUM; then :; else do_encode $UTRACKNUM $LOCATION $OUTPUT; fi
2838                         fi
2839                 fi
2840         fi
2841         if [ "$DOTAG" = "y" ]; then
2842                 if checkstatus encodetrack-$UTRACKNUM; then
2843                         if checkstatus tagtrack-$UTRACKNUM; then :; else do_tag $UTRACKNUM; fi
2844                 fi
2845         fi
2846         if [ "$DOMOVE" = "y" ]; then
2847                 if checkstatus tagtrack-$UTRACKNUM; then
2848                         if checkstatus movetrack-$UTRACKNUM; then :; else do_move $UTRACKNUM; fi
2849                 fi
2850         fi
2851         ) &
2852 done
2853 # Lets move the cue file
2854 if checkstatus cuefile >/dev/null ; then 
2855         do_movecue
2856 fi
2857 # Go through it again and make sure there's no distmp3 stragglers, otherwise
2858 # we'll delete the files they're working on
2859 ## FIXME ## Check also for files which are encoded using PIPEs.
2860 if [ "$DOENCODE" = "y" -a "$USEPIPES" != "y" ]; then
2861         PROCEED=
2862         until [ $PROCEED ]
2863         do
2864                 PROCEED=y
2865                 for LOCATION in $ENCODELOCATIONS
2866                 do
2867                         CHECKTRACK="$(checkstatus encodetracklocation-$LOCATION)"
2868                         # "How can he give us a status update, if he's DEAD?"
2869                         if checkstatus encodetrack-$CHECKTRACK; then
2870                                 continue
2871                         fi
2872                         # Nothing to see here please go quietly back to your homes
2873                         if [ -z "$CHECKTRACK" ]; then continue; fi
2874                         # You're still here? Maybe there is something...
2875                         if checkstatus encodetrack-$CHECKTRACK; then :; else PROCEED= ; break; fi
2876                 done
2877                 # hold up
2878                 if [ ! $PROCEED ]; then sleep 5; fi
2879         done
2880 fi
2881 # If the above didn't catch the stragglers, this will
2882 wait
2883 # Check to see if run_command logged any errors
2884 if [ -f "$ABCDETEMPDIR/errors" ]; then
2885         echo "The following commands failed to run:"
2886         cat "$ABCDETEMPDIR/errors"
2887         # Don't clean up
2888         DOCLEAN=n
2889 fi
2890 if [ "$KEEPWAVS" = "y" ];then
2891         # Don't clean up
2892         DOCLEAN=n
2893 fi
2894 if [ "$DOCLEAN" = "y" ]; then
2895         # Wipe all the evidence
2896         # Gimme gimme gimme some more time!
2897         sleep 5
2898         rm -rf "$ABCDETEMPDIR"
2899         echo "Finished."
2900 else
2901         echo "Finished. Not cleaning $ABCDETEMPDIR."
2902 fi
2903 )
2904 exit 0
2905
2906 # b:is_bash
2907 # vim:tabstop=4