#!/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"

perl -0pi -e '
s@function pickRemoteVideoParticipant\(\)\s*\{.*?\n  \}\n\n  function firstSubscribedTrack\(publications\)\{@function pickRemoteVideoParticipant(){
    if (!lkRoom) return null;
    const remotes = Array.from(lkRoom.remoteParticipants.values());

    const studioReturn = remotes.find(p => String((p && p.identity) || "").trim() === "studio-return") || null;
    if (studioReturn) return studioReturn;

    for (const p of remotes){
      for (const pub of p.videoTrackPublications.values()){
        if (pub.track) return p;
      }
    }
    for (const p of remotes){
      if (p.videoTrackPublications.size > 0) return p;
    }
    return remotes[0] || null;
  }

  function firstSubscribedTrack(publications){@s;

s@function attachRemoteFromParticipant\(p\)\s*\{.*?\n  \}\n\n  function refreshGuestStrip\(\)\{@function attachRemoteFromParticipant(p){
    if (!p){
      clearRemote();
      if (remoteVU) remoteVU.detach();
      return;
    }

    const v = firstSubscribedTrack(p.videoTrackPublications);
    detachRemoteVideo();

    const label = String(p.name || p.identity || "participant");

    if (!v){
      if (els.remoteEmpty) els.remoteEmpty.style.display = "flex";
      if (els.tagRemote) els.tagRemote.textContent = `Remote: ${label}`;
    } else {
      remoteVideoTrack = v;
      try { v.attach(els.remoteVideo); } catch(_){}
      if (els.remoteEmpty) els.remoteEmpty.style.display = "none";
      if (els.tagRemote) els.tagRemote.textContent = `Remote: ${label}`;
    }

    const a = firstSubscribedTrack(p.audioTrackPublications);
    if (remoteVU){
      if (a) remoteVU.attachTrack(a);
      else remoteVU.detach();
    }
  }

  function refreshGuestStrip(){@s
' "$JOINPHP"

echo
echo "Patch complete."
echo
echo "Run:"
echo "php -l \"$JOINPHP\""
echo "sed -n '\''1670,1735p'\'' \"$JOINPHP\""
