#!/usr/bin/env python3

# Apparently the ReplayGain ID3 fields are supposed in upper-case, even though
# Ex Falso has been writing them in lower-case the whole time. (And so has
# foobar2000 at least up to 1.5.6 ...)
#
# https://github.com/quodlibet/quodlibet/issues/3228
# https://wiki.hydrogenaud.io/index.php?title=ReplayGain_2.0_specification#ID3v2
#
# (Note: Spec says that players *should* accept alternate capitalization, as
# well as other formatting quirks.)

import argparse
import mutagen.mp3

replaygain_keys = [
    "REPLAYGAIN_TRACK_GAIN",
    "REPLAYGAIN_TRACK_PEAK",
    "REPLAYGAIN_ALBUM_GAIN",
    "REPLAYGAIN_ALBUM_PEAK",
]

parser = argparse.ArgumentParser()
parser.add_argument("-n", "--dry-run", action="store_true")
parser.add_argument("file", nargs="+")
args = parser.parse_args()

n_good = 0
n_bad = 0

for path in args.file:
    if not path.lower().endswith(".mp3"):
        print("ignoring", path, "(not an MP3 file)")
        continue

    print("processing", path)
    tag = mutagen.mp3.MP3(path)
    dirty = False

    for k in replaygain_keys:
        old = "TXXX:%s" % k.lower()
        new = "TXXX:%s" % k.upper()
        if old in tag:
            if args.dry_run:
                print("  found %r" % tag[old])
            elif new in tag:
                print("  deleting %r (duplicate)" % tag[old])
                del tag[old]
                dirty = True
            else:
                print("  fixing %r" % tag[old])
                value = tag[old]
                del tag[old]
                value.desc = k.upper()
                tag[new] = value
                dirty = True

    if dirty:
        tag.save()
        n_bad += 1
    else:
        n_good += 1

print("done (%d good files, %d bad)" % (n_good, n_bad))
