#!/bin/sh

# Version 0.2
# 2006-09-16

. replaygain_functions.sh

# Check if exactly one directory was specified on command line
if [[ $# != 1 ]] ; then
    echo "Usage: `basename $0` <directory>" >&2
    exit 1
fi

check_environment "$1" # includes pushd, if it does not exit

# If LC_ALL is set, awk might use "," instead of "." as the floating
# point separator for various countries. This would break parsing the
# output of mp3gain, so lets unset it.
unset LC_ALL

LC_NUMERIC=POSIX; export LC_NUMERIC

# Process these files in the working directory
filelist="*.mp3"

# filename prefix for storing time stamp information of all files
timestamp=`tempfile`
set -x
set -v
# Store modification time of all files to be processed
for n in $filelist; do
    touch -r "$n" "${timestamp}-$n"
done

# Let mp3gain calculate the gain values of all files.
# As we give normally more than one file here, album gain is also
# calculated.
$MP3GAIN  $filelist

TMPFILE=`tempfile`

# Write ID3V2 tags
for n in $filelist; do
    # File contains new or updated gain/peak tags in APE
    # format. Let`s read them.
    $MP3GAIN -s c "$n" > $TMPFILE
    TRACK_GAIN=`awk '/^Recommended "Track" dB / { printf("%+.2f dB", $5) }' $TMPFILE`
    ALBUM_GAIN=`awk '/^Recommended "Album" dB / { printf("%+.2f dB", $5) }' $TMPFILE`
    TRACK_PEAK=`awk '/^Max PCM / { printf("%.6f", $7/32768) }' $TMPFILE`
    ALBUM_PEAK=`awk '/^Max Album PCM / { printf("%.6f", $8/32768) }' $TMPFILE`
    
    # Read current ID3V2 gain/peak tags
    $EYED3 -v "$n" > $TMPFILE
    TRACK_GAIN_OLD=`awk '/^<User defined text.*replaygain_track_gain/ { printf("%+.2f dB", $9) }' $TMPFILE`
    ALBUM_GAIN_OLD=`awk '/^<User defined text.*replaygain_album_gain/ { printf("%+.2f dB", $9) }' $TMPFILE`
    TRACK_PEAK_OLD=`awk '/^<User defined text.*replaygain_track_peak/ { printf("%.6f", $9) }' $TMPFILE`
    ALBUM_PEAK_OLD=`awk '/^<User defined text.*replaygain_album_peak/ { printf("%.6f", $9) }' $TMPFILE`
    
    # Do only write those ID3V2 tags that need changing. That way we
    # prevent updating the file, when there was not made any change to
    # the file by mp3gain.

    arg=""
    if [ "$TRACK_GAIN" != "$TRACK_GAIN_OLD" ]; then
	arg="${arg} --set-user-text-frame=\"replaygain_track_gain:$TRACK_GAIN\""
	#$EYED3 --set-user-text-frame="replaygain_track_gain:$TRACK_GAIN" "$n"
    fi
    if [ "$ALBUM_GAIN" != "$ALBUM_GAIN_OLD" ]; then
	arg="${arg} --set-user-text-frame=\"replaygain_album_gain:$ALBUM_GAIN\""
	#$EYED3 --set-user-text-frame="replaygain_album_gain:$ALBUM_GAIN" "$n"
    fi
    if [ "$TRACK_PEAK" != "$TRACK_PEAK_OLD" ]; then
	arg="${arg} --set-user-text-frame=\"replaygain_track_peak:$TRACK_PEAK\""
	#$EYED3 --set-user-text-frame="replaygain_track_peak:$TRACK_PEAK" "$n"
    fi
    if [ "$ALBUM_PEAK" != "$ALBUM_PEAK_OLD" ]; then
	arg="${arg} --set-user-text-frame=\"replaygain_album_peak:$ALBUM_PEAK\""
	#$EYED3 --set-user-text-frame="replaygain_album_peak:$ALBUM_PEAK" "$n"
    fi
    if [ ! -z "$arg" ]; then
      # Write gain information into ID3V2 tags

	# First convert to ID3V2.4 tags
	$EYED3 --to-v2.4 "$n"

	# Now tag it

	# If the command is executed directly, like
	# $EYED3 "$arg" "$n"
	# the shells escaps the arguments wrongly, so the values
	# containing spaces are split into separate arguments. Not
	# sure, what exactly happens here, but see yourself using 
	# set -x
	# set -v
	# $EYED3 "$arg" "$n"
	# exit

	# Therefore we call it indirectly via a temporary
	# file. However, this deactivates the same escaping mechanism
	# for the file name also. Files containing ' or " would not
	# work then. So, we first change the name into something
	# without special characters and rename it back after tagging.

	t2=`tempfile`
	mv "$n" $t2
	echo $EYED3 "$arg" $t2 >$TMPFILE
	. $TMPFILE
	mv $t2 "$n"

	# Let`s look at the result
	$EYED3 -v "$n"
    else
      echo no tags change: $n
      #$EYED3 -v "$n"
    fi

    # Normally it`s better to keep the APE tags, so mp3gain finds them
    # on the next run and does not reprocess the file again. If you
    # never update your files, you can delete the APE tags by
    # uncommenting the next line. Also you may want to delete the APE
    # flags, if your mp3 player gives APE tags priority over ID3V2
    # tags, so you lose artist information (eg. older versions of
    # foobar2000)

    # $MP3GAIN -s d "$n"

    # Restore file modification time
    touch -r "${timestamp}-$n" "$n"
    rm "${timestamp}-$n"
done

# cleanup
rm -f $TMPFILE

