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