#!/usr/bin/env bash
set -euo pipefail

JOINPHP="${1:-/home/itahukamedia/public_html/studio.itahukamedia.com/public/join.php}"
TS="$(date +%Y%m%d_%H%M%S)"

cp -a "$JOINPHP" "$JOINPHP.bak.$TS"
echo "Backup created: $JOINPHP.bak.$TS"

awk '
BEGIN{inserted=0}
{
  if (!inserted && $0 ~ /^  function startVuLoop\(\)\{/){
    print "  function createVUMeter(barEl, dbEl){"
    print "    const SEGMENTS = 20;"
    print "    barEl.innerHTML = \"\";"
    print "    const segs = [];"
    print "    for (let i=0;i<SEGMENTS;i++){"
    print "      const d = document.createElement(\"div\");"
    print "      d.className = \"seg\";"
    print "      if (i >= SEGMENTS-3) d.classList.add(\"hot\");"
    print "      else if (i >= SEGMENTS-7) d.classList.add(\"warn\");"
    print "      barEl.appendChild(d);"
    print "      segs.push(d);"
    print "    }"
    print ""
    print "    return {"
    print "      analyser: null,"
    print "      source: null,"
    print "      data: new Float32Array(2048),"
    print "      setLevelFromDb: function(db){"
    print "        const clamped = Math.max(-60, Math.min(0, db));"
    print "        const norm = (clamped + 60) / 60;"
    print "        const onCount = Math.round(norm * SEGMENTS);"
    print "        for (let i=0;i<SEGMENTS;i++){"
    print "          segs[i].classList.toggle(\"on\", i < onCount);"
    print "        }"
    print "        if (dbEl) dbEl.textContent = `${clamped.toFixed(1)} dB`;"
    print "      },"
    print "      setIdle: function(){"
    print "        for (const s of segs) s.classList.remove(\"on\");"
    print "        if (dbEl) dbEl.textContent = \"— dB\";"
    print "      },"
    print "      attachTrack: function(track){"
    print "        this.detach();"
    print "        const mst = getMediaStreamTrack(track);"
    print "        if (!mst) { this.setIdle(); return; }"
    print "        const ctx = ensureAudioContext();"
    print "        const stream = new MediaStream([mst]);"
    print "        const source = ctx.createMediaStreamSource(stream);"
    print "        const analyser = ctx.createAnalyser();"
    print "        analyser.fftSize = 2048;"
    print "        analyser.smoothingTimeConstant = 0.85;"
    print "        source.connect(analyser);"
    print "        this.source = source;"
    print "        this.analyser = analyser;"
    print "      },"
    print "      detach: function(){"
    print "        try { if (this.source) this.source.disconnect(); } catch(_){}"
    print "        this.source = null;"
    print "        this.analyser = null;"
    print "        this.setIdle();"
    print "      },"
    print "      tick: function(){"
    print "        if (!this.analyser) return;"
    print "        this.analyser.getFloatTimeDomainData(this.data);"
    print "        let sum = 0;"
    print "        for (let i=0;i<this.data.length;i++){"
    print "          const x = this.data[i];"
    print "          sum += x * x;"
    print "        }"
    print "        const rms = Math.sqrt(sum / this.data.length);"
    print "        const db = (rms > 0) ? (20 * Math.log10(rms)) : -60;"
    print "        this.setLevelFromDb(db);"
    print "      }"
    print "    };"
    print "  }"
    print ""
    inserted=1
  }
  print
}
' "$JOINPHP" > "$JOINPHP.tmp"

mv "$JOINPHP.tmp" "$JOINPHP"

echo
echo "Patch complete."
echo
echo "Run:"
echo "php -l \"$JOINPHP\""
echo "grep -n \"function createVUMeter\\|function startVuLoop\" \"$JOINPHP\""
