mkdir -p lossy
find . -type f -iname "*.flac" -print0 | while IFS= read -r -d '' file; do
    rgv=$(metaflac --show-tag=REPLAYGAIN_TRACK_GAIN "$file" | sed 's/^[^=]*=//; s/ //')
    out="./lossy/$(basename "$file" .flac).ogg"

    if [ -z "$rgv" ]; then
        echo "$file: MISSING REPLAYGAIN"
        rgv=0
    fi
    if [ -e "$out" ]; then
        echo "$out: already exists, skipping"
        continue
    fi
    ffmpeg -hide_banner -nostdin -i "$file" -filter:a "alimiter=level_in=$rgv:limit=0.8912:asc=1:level=0:latency=1" -c:a libopus -b:a 224k -map_metadata -1 "$out"
    # docs suggest to oversample for alimiter, but in these recordings peaks are probably occassional, so not a big deal.
done
