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