#!/bin/bash
cd "$(dirname "$(readlink -f "$0")")"
command -v ffmpeg >/dev/null || DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends ffmpeg
python3 - "$@" <<'PY'
import glob, os, re, shutil, subprocess, sys
from mutagen.id3 import ID3
src, dst = "/var/www/mp3_orig", "mp3"
dry = "-n" in sys.argv[1:]
only = [a for a in sys.argv[1:] if a != "-n"]
thr, mindur, margin, maxcut = -50, 0.3, 0.1, 15.0
os.makedirs(src, exist_ok=True)
for f in sorted(glob.glob(os.path.join(dst, "*.mp3"))):
    o = os.path.join(src, os.path.basename(f))
    if not os.path.exists(o):
        shutil.copy2(f, o)
        print("backup: %s" % o)
def analyze(f):
    err = subprocess.run(["ffmpeg", "-hide_banner", "-nostdin", "-i", f, "-map", "0:a:0", "-af", "silencedetect=n=%ddB:d=%s" % (thr, mindur), "-f", "null", "-"], capture_output=True, text=True).stderr
    regions, cur = [], None
    for line in err.splitlines():
        m = re.search(r"silence_start: (-?[\d.]+)", line)
        if m:
            cur = float(m.group(1))
        m = re.search(r"silence_end: (-?[\d.]+)", line)
        if m and cur is not None:
            regions.append((cur, float(m.group(1))))
            cur = None
    times = re.findall(r"time=(\d+):(\d+):([\d.]+)", err)
    dur = int(times[-1][0]) * 3600 + int(times[-1][1]) * 60 + float(times[-1][2])
    if cur is not None:
        regions.append((cur, dur))
    return regions, dur
def maxvol(f, a, b):
    err = subprocess.run(["ffmpeg", "-hide_banner", "-nostdin", "-ss", "%.3f" % a, "-to", "%.3f" % b, "-i", f, "-map", "0:a:0", "-af", "volumedetect", "-f", "null", "-"], capture_output=True, text=True).stderr
    m = re.search(r"max_volume: (-?[\d.]+|-inf) dB", err)
    return -999.0 if not m or m.group(1) == "-inf" else float(m.group(1))
def frames(f):
    try:
        t = ID3(f)
    except Exception:
        return set()
    return {k.split(":")[0] for k in t.keys()}
total, trimmed, warn, fail = 0.0, 0, 0, 0
names = sorted(glob.glob(os.path.join(src, "*.mp3")), key=str.lower)
if only:
    names = [n for n in names if os.path.basename(n) in only]
for o in names:
    name = os.path.basename(o)
    out = os.path.join(dst, name)
    try:
        regions, dur = analyze(o)
        start, end = 0.0, dur
        if regions and regions[0][0] <= 0.05:
            start = max(0.0, regions[0][1] - margin)
        if regions and regions[-1][1] >= dur - 0.05 and regions[-1][0] > start:
            end = min(dur, regions[-1][0] + margin)
        for side, a, b in (("head", 0.0, start), ("tail", end, dur)):
            if b - a > maxcut:
                warn += 1
                mv = maxvol(o, a, b)
                print("WARNING: %s cuts %.2f s at %s (max_volume %.1f dB)" % (name, b - a, side, mv))
                if mv > thr:
                    print("WARNING: %s %s not clearly silent, keeping it" % (name, side))
                    start, end = (0.0, end) if side == "head" else (start, dur)
        if end - start < 1.0:
            raise RuntimeError("almost entirely silent, skipped")
        if start < 0.05:
            start = 0.0
        if dur - end < 0.05:
            end = dur
        cut = start + dur - end
        print("%s\t%.3f\t%.3f\t%.3f\t%s" % ("trim" if cut else "keep", start, dur - end, dur, name))
        if dry:
            continue
        tmp = os.path.join(dst, ".trim_tmp.mp3")
        if cut:
            cmd = ["ffmpeg", "-hide_banner", "-nostdin", "-v", "error", "-y", "-i", o]
            cmd += (["-ss", "%.3f" % start] if start else []) + (["-to", "%.3f" % end] if end < dur else [])
            cmd += ["-map", "0", "-map_metadata", "0", "-c", "copy", "-id3v2_version", "3", "-write_id3v1", "1" if b"TAG" == open(o, "rb").read()[-128:][:3] else "0", tmp]
            subprocess.run(cmd, check=True)
            if not frames(o) <= frames(tmp):
                ID3(o).save(tmp, v2_version=3)
            if not frames(o) <= frames(tmp):
                raise RuntimeError("tags lost: %s" % sorted(frames(o) - frames(tmp)))
            shutil.copystat(o, tmp)
            os.chmod(tmp, os.stat(o).st_mode)
            os.chown(tmp, os.stat(o).st_uid, os.stat(o).st_gid)
            os.replace(tmp, out)
            trimmed += 1
            total += cut
        elif not os.path.exists(out) or open(o, "rb").read() != open(out, "rb").read():
            shutil.copy2(o, tmp)
            os.replace(tmp, out)
    except Exception as e:
        fail += 1
        print("ERROR: %s: %s" % (name, e))
print("files=%d trimmed=%d removed=%.1fs warnings=%d errors=%d%s" % (len(names), trimmed, total, warn, fail, " (dry run)" if dry else ""))
sys.exit(1 if fail else 0)
PY
