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

if [ "$#" -lt 1 ]; then
  echo "Usage: $0 /path/to/studio/public"
  echo "Example: $0 /home/itahukamedia/public_html/studio.itahukamedia.com/public"
  exit 1
fi

ROOT="$1"
JOIN="$ROOT/join.php"

if [ ! -f "$JOIN" ]; then
  echo "Missing file: $JOIN" >&2
  exit 1
fi

if ! command -v php >/dev/null 2>&1; then
  echo "ERROR: php CLI not found in PATH." >&2
  exit 1
fi

STAMP="$(date +%Y%m%d_%H%M%S)"
cp -a "$JOIN" "$JOIN.bak.$STAMP"
echo "Backup created: $JOIN.bak.$STAMP"

php -- "$JOIN" <<'PHP'
<?php
$joinPath = $argv[1] ?? '';
if ($joinPath === '') { fwrite(STDERR, "Missing join.php path\n"); exit(1); }

function fail($msg){ fwrite(STDERR, $msg . PHP_EOL); exit(1); }
function read_strict($p){ $c = file_get_contents($p); if ($c === false) fail("Cannot read: $p"); return $c; }
function write_strict($p, $c){ if (file_put_contents($p, $c) === false) fail("Cannot write: $p"); }
function patch_once(&$text, $search, $replace, $label){
  if (strpos($text, $replace) !== false) {
    echo "Already patched: $label\n";
    return;
  }
  $count = substr_count($text, $search);
  if ($count !== 1) fail("Patch failed for $label: expected 1 exact match, got $count");
  $text = str_replace($search, $replace, $text);
  echo "Patched: $label\n";
}

$join = read_strict($joinPath);

/*
  Surgical patch: only these five changes
  1) boot() room default: remove camA fallback, use PHP roomName
  2) buildShare() room fallback: remove camA fallback, use PHP roomName
  3) join() post-connect old OFF block: replace with immediate full AV start
  4) pickRemoteVideoParticipant(): use studio-return only
  5) refreshGuestStrip(): exclude studio-return from guest strip
*/

/* 1) boot room source */
patch_once(
  $join,
  <<<'TXT'
    if (els.room) els.room.value = qsGet("room", "camA");
TXT,
  <<<'TXT'
    if (els.room) els.room.value = qsGet("room", <?php echo json_encode($roomName); ?>);
TXT,
  'boot room uses PHP roomName'
);

/* 2) share room source */
patch_once(
  $join,
  <<<'TXT'
    base.searchParams.set("room", ((els.room && els.room.value.trim()) || "camA"));
TXT,
  <<<'TXT'
    base.searchParams.set("room", ((els.room && els.room.value.trim()) || <?php echo json_encode($roomName); ?>));
TXT,
  'buildShare uses PHP roomName'
);

/* 3) post-connect old OFF block -> full AV start */
patch_once(
  $join,
  <<<'TXT'
      buildShare();
      refreshGuestStrip();

      // local screen stays "Not publishing" until MIC/CAM pressed
      detachLocal();
      if (localVU) localVU.setIdle();

      await enumerateDevices().catch(()=>{});
TXT,
  <<<'TXT'
      buildShare();
      refreshGuestStrip();

      // Start publishing BOTH camera and microphone immediately after join
      await ensureLocalCam();
      await ensureLocalMic();
      attachLocal();
      if (localVU && localAudio) localVU.attachTrack(localAudio);
      syncButtons();
      refreshGuestStrip();

      await enumerateDevices().catch(()=>{});
TXT,
  'join post-connect starts full AV'
);

/* 4) return participant selector */
patch_once(
  $join,
  <<<'TXT'
  function pickRemoteVideoParticipant(){
    if (!lkRoom) return null;
    const remotes = Array.from(lkRoom.remoteParticipants.values());
    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;
  }
TXT,
  <<<'TXT'
  function pickRemoteVideoParticipant(){
    if (!lkRoom) return null;
    const remotes = Array.from(lkRoom.remoteParticipants.values());
    return remotes.find(p => String((p && p.identity) || "").trim() === "studio-return") || null;
  }
TXT,
  'pickRemoteVideoParticipant uses studio-return'
);

/* 5) guest strip excludes studio-return */
patch_once(
  $join,
  <<<'TXT'
    const participants = [];
    if (lkRoom.localParticipant) participants.push({ key:"local", p: lkRoom.localParticipant, isLocal:true });
    for (const p of lkRoom.remoteParticipants.values()){
      participants.push({ key: p.sid || p.identity || String(Math.random()), p, isLocal:false });
    }
TXT,
  <<<'TXT'
    const participants = [];
    if (lkRoom.localParticipant) participants.push({ key:"local", p: lkRoom.localParticipant, isLocal:true });
    for (const p of lkRoom.remoteParticipants.values()){
      if (String((p && p.identity) || "").trim() === "studio-return") continue;
      participants.push({ key: p.sid || p.identity || String(Math.random()), p, isLocal:false });
    }
TXT,
  'refreshGuestStrip excludes studio-return'
);

write_strict($joinPath, $join);
echo "Done: $joinPath\n";
PHP

echo
echo "Patch complete."
echo
echo "Run syntax check:"
echo "php -l \"$JOIN\""
echo
echo "Then hard-refresh ONLY join.php and test."
echo "This patch changed only:"
echo " 1) boot room fallback"
echo " 2) share room fallback"
echo " 3) join post-connect full AV start"
echo " 4) remote participant selector"
echo " 5) guest strip filter"
