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